<template>
  <basic-container>
    <avue-crud
      ref="crud"
      :option="option"
      :data="data"
      @on-load="onLoad"
      :page.sync="page"
      :permission="permissionList"
      @row-save="rowSave"
      @current-change="currentChange"
      @size-change="sizeChange"
      @row-update="rowUpdate"
      @refresh-change="refreshChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      v-model="form"
      :table-loading="loading"
    >
      <template slot="status" slot-scope="{ row }">{{ row.status }}</template>
      <template slot="menuLeft">
        <el-button
          v-if="vaildData(permission.manage_station_inviteCode_upload, false)"
          size="small"
          @click.stop="handleImport"
          type="primary"
          >批量上传</el-button
        >
        <el-button
          size="small"
          @click.stop="distributionCode"
          type="primary"
          >分配邀请码</el-button
        >
      </template>
      <template v-slot:menu="{ row }">
        <el-button
          type="text"
          size="small"
          @click.stop="rowEdit(row)"
          v-if="
            row.status === '未绑定' &&
            vaildData(permission.manage_station_inviteCode_edit, false)
          "
          >绑定</el-button
        >
      </template>
    </avue-crud>
    <el-dialog
      title="批量上传"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
        :upload-before="beforeAvatarUpload"
        :upload-error="uploadError"
      >
        <template slot="excelTemplate">
          <el-button
            type="primary"
            @click="handleTemplate()"
            :loading="templateLoading"
          >
            点击下载
            <i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>

    <!-- 分配邀请码 -->
    <el-dialog
      title="分配邀请码"
      :visible.sync="distributionCodeDialog"
      append-to-body
      width="30%">
      <el-form :model="inviteCodeForm" :rules="inviteCodeRules" ref="inviteCode" label-width="100px" class="demo-ruleForm">
        <el-form-item label="工作站:" prop="stationId">
          <el-select v-model="inviteCodeForm.stationId" placeholder="请选择" @change="inviteCodeName"
          >
            <el-option
              v-for="item in stationIdList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分配数量:" prop="strip">
          <span class="inviteCodeStrip"
                :class="{'inviteCodeStripActive': inviteCodeForm.count === 5}"
                style="margin-right: 10px;"
                @click="inviteCodeForm.count = 5">5</span>
          <span class="inviteCodeStrip"
                :class="{'inviteCodeStripActive':
                inviteCodeForm.count === 10}"
                @click="inviteCodeForm.count = 10">10</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="inviteCodeClose">取 消</el-button>
        <el-button type="primary" @click="inviteCodeSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配邀请码"
      :visible.sync="qRCodeDialog"
      append-to-body
      width="30%">
      <div>
        <p>您当前选择了 <span style="color: red;">{{inviteCodeForm.count}}</span> 条邀请码，确定分配给 <span style="color:red;">{{inviteCodeFormName}}</span> 吗？</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="qRCodeDialog = false">取 消</el-button>
        <el-button type="primary" :loading="codeLoading" @click="qRCodeDialogOk">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { mapGetters } from "vuex";
import { getList, add, edit, importInviteCode, inviteAllocation } from "@/api/manage/inviteCode";
import { check18IdCardNo, isExcel, isMobile } from "@/util/validate";
import { getTemplate } from "@/api/resource/template";
import { getStationDic, StationDic } from "@/api/manage/station";
import { excelAccept } from "@/common/accept";


export default {
  name: "manage_station_inviteCode",
  data() {
    const validateMobile = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入手机号"));
      } else {
        if (isMobile(value)) {
          callback();
        } else {
          callback(new Error("手机号格式不正确"));
        }
      }
    };
    const validateIdNum = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入身份证"));
      } else {
        if (check18IdCardNo(value)) {
          callback();
        } else {
          callback(new Error("身份证格式不正确"));
        }
      }
    };
    return {
      inviteCodeForm: {
        count: 5
      },
      inviteCodeRules: {
        stationId: [
          { required: true, message: '请选择工作站', trigger: 'blur' }
        ],
        count: [
          { required: true, message: '请选择数量', trigger: 'blur' }
        ],
      },
      stationIdList: [],
      distributionCodeDialog: false,
      qRCodeDialog: false,
      inviteCodeFormName: '',
      searchTxt: "",
      excelBox: false,
      excelForm: {},

      query: {},
      file: {},
      option: {
        index: true,
        indexLabel: "序号",
        idKey: "id",
        delBtn: false,
        border: true,
        editBtn: false,
        searchShow: true,
        searchMenuSpan: 4,
        loading:true,
        column: [
          {
            label: "所属分组",
            prop: "groupType",
            search: true,
            searchSpan: 4,
            type: "select",
            rules: [
              {
                required: true,
                message: "请选择所属分组",
              },
            ],
            dicData: [
              {
                label: "企嘉云",
                value: 0,
              },
              {
                label: "人保",
                value: 1,
              },
              {
                label: "灯塔中心",
                value: 3,
              },
            ],
          },

          {
            type: "tree",
            label: "所属工作站",
            prop: "stationId",
            //display: false,
            search: true,
            searchSpan: 4,
            searchLabelWidth: 87,
            dicUrl: getStationDic(),
            props: {
              label: "stationName",
              value: "stationId",
            },
            dicFormatter(resp) {
              return resp.data;
            },
          },
          {
            label: "邀请码",
            prop: "inviteCode",
            search: true,
            searchSpan: 4,
            rules: [
              {
                required: true,
                message: "请输入邀请码",
                trigger: "blur",
              },
            ],

            editDisabled: true,
            maxlength:14,
            showWordLimit:true,
          },
          {
            label: "姓名",
            prop: "realName",
          },
          {
            label: "身份证号",
            prop: "idNumber",
            rules: [
              {
                required: true,
                validator: validateIdNum,
                trigger: "blur",
              },
            ],
          },
          {
            label: "手机号",
            prop: "phone",
            rules: [
              {
                required: true,
                validator: validateMobile,
                trigger: "blur",
              },
            ],
          },
          {
            label: "状态",
            prop: "status",
            search: true,
            searchSpan: 4,
            type: "select",
            dicData: [
              {
                label: "已绑定",
                value: 1,
              },
              {
                label: "未绑定",
                value: 0,
              },
            ],
            display: false,
          },
          {
            label: "是否分配",
            prop: "isEnabled",
            search: true,
            searchSpan: 4,
            type: "select",
            dicData: [
              {
                label: "已分配",
                value: 1,
              },
              {
                label: "未分配",
                value: 0,
              },
            ],
            display: false,
          },
          {
            label: "备注",
            prop: "remarks",
            display: false,
            hide: true,
          },
        ],
      },
      data: [],
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      codeLoading: false
    };
  },

  created() {
    StationDic().then(res => {
      this.stationIdList = res.data.data
    })
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permission.manage_station_inviteCode_add,
          false
        ),
      };
    },
    excelOption() {
      return {
        submitBtn: false,
        emptyBtn: false,
        templateLoading: false,
        column: [
          {
            label: "文件上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "文件上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            accept: excelAccept,
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: importInviteCode(),
          },
          {
            label: "数据覆盖",
            prop: "isCovered",
            type: "switch",
            align: "center",
            width: 80,
            dicData: [
              {
                label: "否",
                value: 0,
              },
              {
                label: "是",
                value: 1,
              },
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: "请选择是否覆盖",
                trigger: "blur",
              },
            ],
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      };
    },
  },
  mounted() {},
  watch: {},
  methods: {
    inviteCodeName (v) {
      var inviteCodeFormName = this.stationIdList.find(e => {
        return e.stationId === v
      })
      this.inviteCodeFormName = inviteCodeFormName.stationName
    },
    qRCodeDialogOk () {
      this.codeLoading = true
      inviteAllocation(this.inviteCodeForm).then(() => {
        this.$message.success('分配成功')
        this.refreshChange()
        this.codeLoading = false
        this.qRCodeDialog = false
        this.distributionCodeDialog = false
      }).catch(() => {
        this.codeLoading = false
      })
    },
    inviteCodeSubmit (){
      this.$refs['inviteCode'].validate((valid) => {
        if (valid) {
          this.qRCodeDialog = true
        } else {
          return false;
        }
      });
    },
    inviteCodeClose(){
      this.distributionCodeDialog = false
    },
    distributionCode(){
      this.distributionCodeDialog = true
    },
    handleImport() {
      this.excelBox = true;
    },
    handleTemplate() {
      this.templateLoading = true;
      getTemplate("yqm")
        .then((rep) => {
          this.templateLoading = false;
          window.open(rep.data.data);
        })
        .catch(() => {
          this.templateLoading = false;
        });
    },
    beforeAvatarUpload(file, done, loading) {
      this.file = file;
      if (!isExcel(file)) {
        loading();
        this.$message.error("上传参保信息只能是 .xls,.xlsx 标准格式文件!");
      } else {
        done();
      }
    },
    uploadAfter(res, done) {
      if (!(res instanceof Error)) {
        this.excelBox = false;
      }
      this.refreshChange();
      done();
    },
    uploadError(error) {
      if (error) {
        this.$message.error(error);
      }
    },
    searchInfo() {
      this.onLoad(this.page);
    },
    rowSave(row, done,loading) {
      this.$refs.crud.validate((valid) => {
        if (valid) {
          add(
            row.inviteCode,
            row.realName,
            row.idNumber,
            row.phone,
            row.groupType,
            row.remarks,
            row.stationId
          ).then(
            () => {
              this.$message.success('添加成功')
              done();
              this.onLoad(this.page);
            },
            (error) => {
              window.console.log(error);
              loading()

            }
          );
        }
      });
    },
    rowEdit(row) {
      this.$refs.crud.rowEdit(row);
    },
    rowUpdate(row, index, done, loading) {
      if (row.status == "已绑定") {
        row.status = 1;
      } else {
        row.status = 0;
      }
      this.$refs.crud.validate((valid) => {
        if (valid) {
          edit(
            row.id,
            row.inviteCode,
            row.realName,
            row.idNumber,
            row.phone,
            row.groupType,
            row.remarks,
            row.status,
            row.stationId
          ).then(
            () => {
              this.$message.success('绑定成功')
              done(row);
              this.onLoad(this.page);
            },
            (error) => {
              window.console.log(error);
              loading();
            }
          );
        }
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading=true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(this.query, params)
      ).then((res) => {
        const data = res.data.data;
        for (const key in data.records) {
          if (data.records[key].status == "1") {
            data.records[key].status = "已绑定";
          } else {
            data.records[key].status = "未绑定";
          }
        }
        this.data = data.records;
        this.page.total = data.total;
        this.loading=false;
      });
    },
  },
};
</script>
<style>
  .inviteCodeStrip{
    display: inline-block;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 10px;
    border: 1px solid #e3e3e3;
    cursor: pointer;
  }
  .inviteCodeStripActive {
    color: #FFFFFF;
    background-color: #409EFF;
  }
</style>
