<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="60%" center @close="close">
    <div class="content">
      <div class="tips" v-if="type === 'add'">
        全职学术推广员待事业部备案管理员核验后启用
      </div>
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" center :close-on-click-modal="false">
        <el-form-item label="人员名称" prop="realName">
          <el-input v-model="form.realName" :disabled="formDisabled" />
        </el-form-item>
        <el-form-item label="手机号" prop="username">
          <el-input v-model="form.username" maxlength="11" :disabled="formDisabled || editDisabled" />
        </el-form-item>
        <el-form-item label="身份证号" prop=" ">
          <el-input v-model="form.idCardNumber" :disabled="editTypeDisabled || formDisabled" />
        </el-form-item>
        <el-form-item label="人员角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择" class="w100" @change="roleChange" :disabled="formDisabled">
            <el-option label="全职学术推广员" value="5"> </el-option>
            <el-option label="服务供应商管理员" value="37"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="派工方" prop="deptId">
          <el-select v-model="form.deptId" clearable class="w100" @change="deptIdChange" :disabled="formDisabled">
            <el-option v-for="item in deptLists" :key="item.deptId" :label="item.name" :value="item.deptId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启停状态" prop="lockFlag">
          <el-radio-group v-model="form.lockFlag">
            <el-radio label="0" border :disabled="lockFlagDisabled">活跃</el-radio>
            <el-radio label="9" border>{{ radioTitle }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备案上传" prop="certFileIds">
          <uploadCom :disabled="formDisabled" @updateInfo="list => updateInfo(list, 'certFileIds')" :info="form.certFileIds" :show="true" key="certFileIds" />
        </el-form-item>
        <el-form-item label="绑定药品" prop="certFileIds" v-if="type == 'review'">
          <el-select v-model="form.productIds" multiple placeholder="请选择" class="w100">
            <el-option v-for="item in productIdsList" :key="item.drug_id" :label="item.drug_name" :value="item.drug_id"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer" v-if="type == 'add'">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitInfo">确 定</el-button>
    </span>
    <span slot="footer" class="dialog-footer" v-if="type == 'review'">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="reviewBtn">通 过</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {salesmanCreateApi} from '@/api/admin/user';
import uploadCom from '@/components/uploadCom/uploadCom';
import {getListByDeptApi, getCertDetailApi, getWmdadrugentdrugtableList, certProdBindApi, getDeptList4} from '@/api/admin/role';
import {putObj} from '@/api/admin/user';

import {mapGetters} from 'vuex';
export default {
  components: {uploadCom},
  data() {
    return {
      dialogVisible: false,
      formDisabled: false,
      editDisabled: false,
      deptLists: [],
      productIdsList: [],
      currentInfo: {},
      certInfo: {},
      title: '',
      type: '',
      editType: '',
      lockFlagDisabled: false,
      editTypeDisabled: false,
      radioTitle: '待验证',
      form: {
        realName: '',
        username: '',
        phone: '',
        idCardNumber: '',
        role: '',
        deptId: '',
        lockFlag: '',
        certFileIds: [],
        areaCodes: [],
        productIds: []
      },
      rules: {
        realName: [{required: true, message: '请输入正确人员名称'}, {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}],
        username: [
          {
            required: true,
            pattern: /^[0-9]*$/g,
            message: '请输入正确的手机号格式'
          },
          {min: 11, max: 11, message: '长度在 11 个字符', trigger: 'blur'}
        ],
        idCardNumber: [
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X)$)/,
            message: '请输入正确的身份证号格式，如存在x请输入大写',
            trigger: 'blur'
          }
        ],
        deptId: [
          {
            required: true,
            message: '请选择派工方',
            trigger: 'blur'
          }
        ],
        role: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ],
        lockFlag: [{required: true, message: '请选择状态', trigger: 'blur'}]
      }
    };
  },
  computed: {
    ...mapGetters(['permissions', 'userInfo'])
  },
  created() {
    this.getListByDept();
  },
  methods: {
    roleChange(e) {
      if (e == 5) {
        this.lockFlagDisabled = true;
        this.form.lockFlag = '9';
        this.radioTitle = '待验证';
      } else if (e == 37) {
        this.lockFlagDisabled = false;
        this.form.lockFlag = '0';
        this.radioTitle = '休眠';
      }
    },
    show() {
      this.title = '新增服务商管理员';
      this.type = 'add';
      this.editType = '';
      this.formDisabled = false;
      this.editTypeDisabled = false;
      this.dialogVisible = true;
    },

    editFn(row) {
      this.currentInfo = row;
      this.editType = 'edit';
      this.type = 'add';
      if (row.idCardNumber) {
        this.editTypeDisabled = true;
      }
      this.editDisabled = true;
      this.form = {
        realName: row.realname,
        username: row.username,
        idCardNumber: row.idCardNumber,
        role: String(row.role[0]),
        deptId: row.deptId,
        lockFlag: row.lockFlag
      };
      if (this.form.role == '5') {
        this.lockFlagDisabled = true;
        this.form.lockFlag = '9';
      } else {
        this.lockFlagDisabled = false;
      }

      this.dialogVisible = true;
    },
    reviewFn(row) {
      this.title = '审核沟通专员';
      this.type = 'review';
      this.currentInfo = row;
      this.dialogVisible = true;
      this.form = {
        realName: row.realname,
        username: row.username,
        idCardNumber: row.idCardNumber,
        deptId: row.deptId,
        role: String(row.role[0]),
        lockFlag: row.lockFlag
      };
      this.getCertDetail();
      this.formDisabled = true;
    },

    async getCertDetail() {
      const res = await getCertDetailApi(this.currentInfo.userId);
      if (res.data.code === 0 && res.data.data.length) {
        let arr = res.data.data.map(item => {
          if (item.file) {
            const obj = {
              fileId: item.file.id,
              fileName: item.file.original,
              url: item.file.path
            };
            return obj;
          }
        });
        this.$set(this.form, 'certFileIds', arr);
        this.certInfo = res.data.data[0];
      }

      const resA = await getWmdadrugentdrugtableList();
      if (resA.data.code === 0) {
        this.productIdsList = resA.data.data;
      }
    },
    async getListByDept() {
      const res = await getDeptList4();
      this.deptLists = res.data.data;
    },
    deptIdChange(e) {
      const curr = this.deptLists.find(item => item.deptId === e);
      if (curr) {
        this.form.areaCodes = curr.areaCodes;
      }
    },

    submitInfo() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let fileIds = [];
          if (this.form.certFileIds) {
            fileIds = this.form.certFileIds.map(item => item.fileId);
          }
          let obj = {
            username: this.form.username,
            phone: this.form.username,
            realName: this.form.realName,
            role: [this.form.role],
            lockFlag: this.form.lockFlag,
            idCardNumber: this.form.idCardNumber,
            deptId: this.form.deptId,
            areaCodes: this.form.areaCodes,
            certFileIds: fileIds
          };
          let res;
          let msg;
          if (this.editType === 'edit') {
            obj.userId = this.currentInfo.userId;
            obj.realname = obj.realName;
            res = await putObj(obj);
            msg = '更新成功';
          } else {
            res = await salesmanCreateApi(obj);
            msg = '新增成功';
          }

          if (res.data.code == 0) {
            this.$message.success(msg);
            this.close();
            this.$emit('addSuccess');
          }
        }
      });
    },
    updateInfo(list, type) {
      this.form[type] = list;
      this.$refs.ruleForm.validateField(type);
    },
    async reviewBtn() {
      const obj = {
        certId: this.certInfo.certificateId,
        productIds: this.form.productIds,
        userId: this.currentInfo.userId
      };
      const res = await certProdBindApi(obj);
      if (res.data.data) {
        this.$message.success('备案成功');
        this.close();
        this.$emit('addSuccess');
      }
    },
    close() {
      this.$refs.ruleForm.resetFields();
      this.dialogVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.tips {
  font-size: 22px;
  color: red;
  text-align: center;
  font-weight: 600;
  margin-bottom: 20px;
}
</style>
