<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="960px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="isView ? '查看资质' : isUpdate ? '修改资质' : '添加资质'"
    @update:visible="updateVisible"
    :maxable="true"
  >
    <header-title title="基本信息"></header-title>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="10">
          <el-form-item label="资质类型:" prop="certificationType">
            <el-select
              style="width: 100%"
              :disabled="isView"
              v-model="form.certificationType"
              @change="changeCertificationType"
              filterable
            >
              <el-option
                v-for="item in qualificationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="编码:" prop="code">
            <el-input
              :disabled="isView"
              v-model="form.code"
              clearable
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="类型:" prop="type">
            <el-select
              style="width: 100%"
              :disabled="isView"
              v-model="form.type"
              filterable
            >
              <el-option
                v-for="item in typeList"
                :key="item.dictCode"
                :label="item.dictValue"
                :value="item.dictCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="等级:" prop="level">
            <el-select
              style="width: 100%"
              :disabled="isView"
              v-model="form.level"
              filterable
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in levelOptions"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label="名称:" prop="name">
            <el-input
              :disabled="isView"
              v-model="form.name"
              readonly
              clearable
              @click.native="handleClick"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label="附件:" prop="accessory">
            <fileUpload
              v-if="!isView"
              v-model="filedList"
              :show-file-list="false"
              module="main"
              @input="uploadedSuccess($event, form)"
              :limit="1"
            />
            <div v-if="form.accessory?.storePath">
              <span>{{ form.accessory.name }}</span>
              <el-button
                style="margin-left: 10px"
                size="mini"
                type="primary"
                @click="downloadFile(form.accessory.storePath, form)"
                >下载</el-button
              >
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label="有效时间:" prop="date">
            <el-date-picker
              :disabled="isView"
              v-model="form.date"
              type="daterange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <vendorDialog
      ref="vendorDialogRef"
      @success="confirmSelection"
    ></vendorDialog>
    <staffSelection
      ref="staffSelection"
      @confirm="confirmSelection"
    ></staffSelection>
    <clientDialog
      ref="clientSelection"
      @success="confirmSelection"
    ></clientDialog>

    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button v-if="isView" type="primary" @click="updateVisible(false)">
        确定
      </el-button>
      <el-button v-else type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import clientDialog from './clientDialog.vue';
  import vendorDialog from './vendorDialog.vue';
  import staffSelection from './staffSelection.vue';
  import fileUpload from '@/components/upload/fileUpload';
  import { getFile } from '@/api/system/file';
  import {
    saveProfessionCertification,
    getProfessionCertificationById,
    updateProfessionCertificationById
  } from '@/api/factoryModel';
  export default {
    components: {
      fileUpload,
      vendorDialog,
      staffSelection,
      clientDialog
    },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
      isView: Boolean,
      controlList: Array,
      typeList: Array
    },
    data() {
      const defaultForm = function () {
        return {
          id: '',
          certificationType: '',
          code: '',
          personnelIds: '',
          level: '',
          name: '',
          type: '',
          status: 0,
          accessory: {},
          date: '小时'
        };
      };
      return {
        qualificationOptions: [
          {
            label: '客户资质',
            value: '1'
          },
          {
            label: '供应商资质',
            value: '2'
          },
          {
            label: '个人资质',
            value: '3'
          }
        ],

        filedList: [],
        defaultForm,
        // 表单数据
        form: defaultForm(),
        moneyOptions: [
          {
            label: '元',
            value: '元'
          }
        ],
        timeOptions: [
          {
            label: '小时',
            value: '小时'
          },
          {
            label: '天',
            value: '天'
          },
          {
            label: '月',
            value: '月'
          }
        ],
        levelOptions: [
          {
            label: '初级',
            value: '1'
          },
          {
            label: '中级',
            value: '2'
          },
          {
            label: '高级',
            value: '3'
          }
        ],
        // 表单验证规则
        rules: {
          name: [{ required: true, message: '请输入名称', trigger: 'change' }],
          code: [{ required: true, trigger: 'blur', message: '请输入编码' }],
          date: [{ required: true, message: '请选择资质', trigger: 'change' }],
          type: [{ required: true, message: '请选择类型', trigger: 'change' }]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        chooseItem: null
      };
    },
    methods: {
      changeCertificationType(value) {
        this.form.certificationType = value;
        this.form.name = '';
        this.form.personnelIds = '';
      },
      handleClick() {
        switch (this.form.certificationType) {
          case '1':
            this.$refs.clientSelection.open();
            break;
          case '2':
            this.$refs.vendorDialogRef.open();
            break;
          case '3':
            this.$refs.staffSelection.open([]);
            break;
        }
      },
      confirmSelection(data) {
        console.log(data);
        this.form.personnelIds = data.map((item) => item.id).join(',');
        this.form.name = data.map((item) => item.name).join(',');
        this.$forceUpdate();
      },
      downloadFile(url, form) {
        console.log(form);
        getFile({ objectName: url }, '附件');
      },
      uploadedSuccess(data, row) {
        console.log(data, row);
        row.accessory.storePath = data[0].storePath;
        row.accessory.name = data[0].name;
        this.filedList = [];
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          console.log(this.form);
          if (!this.isUpdate) {
            delete this.form.id;
          }
          this.form.startTime = this.form.date[0];
          this.form.endTime = this.form.date[1];
          this.loading = true;
          let apiStr = null;
          if (this.isUpdate) {
            apiStr = updateProfessionCertificationById;
          } else {
            apiStr = saveProfessionCertification;
          }
          apiStr(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success((this.isUpdate ? '修改' : '新建') + '成功');
              this.updateVisible(false);
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              // this.$message.error(e.message);
            });
        });
      },
      /* 更新visible */
      updateVisible(value) {
        this.form = { ...this.defaultForm() };
        this.$emit('update:visible', value);
      }
    },

    watch: {
      async visible(visible) {
        if (visible) {
          if (this.data) {
            const res = await getProfessionCertificationById(this.data.id);
            console.log(res);
            this.$util.assignObject(this.form, {
              ...res
            });
            this.form.date = [res.startTime, res.endTime];
            this.isUpdate = true;
            console.log(this.form);
          } else {
            this.filedList = [];
            this.form = { ...this.defaultForm() };
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm() };
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .hourCostStyle {
    display: flex;
    > div {
      margin-right: 10px;
    }
    > div:last-child {
      margin-right: 0;
    }
  }
</style>
