<template>
  <!-- 上传 -->
  <ele-modal
    :title="title"
    :visible.sync="dialogVisible"
    @close="close"
    width="60%"
    :maxable="true"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item prop="holderType" label="持证类型">
            <el-select
              style="width: 100%"
              v-model="form.holderType"
              @change="holderTypeChange"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in holderTypeOptions"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item prop="type" label="证件类型">
            <DictSelection
              v-model="form.type"
              dictName="证件类型"
              v-if="['1'].includes(form.holderType)"
            ></DictSelection>
            <DictSelection
              v-model="form.type"
              dictName="客户/供应商资质类型"
              v-if="['2', '3', '4', '5', '6'].includes(form.holderType)"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item prop="code" label="证照编号">
            <el-input placeholder="请输入" v-model="form.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item label="等级:" prop="level">
            <el-select style="width: 100%" 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-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item prop="status" label="状态">
            <DictSelection
              v-model="form.status"
              dictName="规则状态"
            ></DictSelection>
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item prop="holder" label="持证对象">
            <el-input
              v-if="form.holderType != 2"
              v-model="form.holder"
              clearable
              readonly
              placeholder="请选择"
              @click.native="openStaffSelection"
            ></el-input>
            <ele-tree-select
              v-if="form.holderType == 2"
              ref="tree"
              clearable
              :data="companyData"
              label-key="name"
              value-key="id"
              default-expand-all
              v-model="form.holder"
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item label="颁发时间">
            <el-date-picker
              style="width: 100%"
              v-model="form.enactorTime"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item prop="date" label="有效期至">
            <el-date-picker
              style="width: 100%"
              v-model="form.date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 24 } : { span: 24 }">
          <el-form-item prop="fileObj" label="附件">
            <fileMain v-model="form.fileObj" />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 24 } : { span: 24 }">
          <el-form-item prop="remark" label="备注">
            <el-input
              placeholder="请输入"
              v-model="form.remark"
              type="textarea"
              :rows="3"
              :resize="`none`"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <staffSelection
      ref="staffSelection"
      @confirm="confirmStaffSelection"
    ></staffSelection>
    <productTable ref="productTableRef" />
    <supplierSelection
      ref="supplierSelectionRef"
      @confirm="confirmStaffSelection"
    />
    <customerSelection
      ref="customerSelectionRef"
      @confirm="confirmStaffSelection"
    />
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="save" type="primary">保 存</el-button>
      <el-button size="small" @click="close">关 闭</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import staffSelection from './staffSelection.vue';
  import { saveOrEdit, getPhotoInfo } from '@/api/documentManagement';
  // import fileMain from '@/components/addDoc/index.vue';

  import { getCode } from '@/api/ruleManagement/matter';
  import productTable from './productTable.vue';
  import supplierSelection from './supplierSelection.vue';
  import customerSelection from './customerSelection.vue';
  import { listOrganizations } from '@/api/system/organization';
  import { holderTypeOptions } from '@/enum/dict.js';
  const defaultForm = {
    code: '',
    holder: '',
    holderId: '',
    type: '',
    date: [],
    fileObj: [],
    holderType: '4',
    status: 1
  };
  export default {
    components: {
      staffSelection,
      productTable,
      supplierSelection,
      customerSelection,
      // fileMain
    },
    //注册组件
    data() {
      return {
        dialogVisible: false,
        levelOptions: [
          {
            label: '初级',
            value: '1'
          },
          {
            label: '中级',
            value: '2'
          },
          {
            label: '高级',
            value: '3'
          }
        ],
        rules: {
          code: [
            { required: true, trigger: 'blur', message: '请输入证照编号' }
          ],
          // level: [{ required: true, trigger: 'change', message: '选择等级' }],
          type: [
            { required: true, trigger: 'change', message: '请选择证件类型' }
          ],
          date: [
            { required: true, trigger: 'change', message: '请选择有效期' }
          ],
          holder: [
            { required: true, trigger: 'change', message: '请选择持证对象' }
          ],
          status: [
            { required: true, trigger: 'change', message: '请选择状态' }
          ],
          fileObj: [{ required: true, trigger: 'change', message: '请选择' }]
        },
        form: { ...defaultForm },
        title: '新增',
        holderTypeOptions,
        companyData: [] //公司分类
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {
      this.getCompanyData();
    },
    methods: {
      //选择负责人
      confirmStaffSelection(data) {
        console.log(data);
        this.form.holderId = data.map((item) => item.id).join(',');

        this.form.holder = data.map((item) => item.name).join(',');
        this.$forceUpdate();
        console.log(this.form);
      },
      openStaffSelection() {
        if (this.form.holderType == 1) {
          this.$refs.staffSelection.open([]);
        } else if (this.form.holderType == 3 || this.form.holderType == 6) {
          this.$refs.supplierSelectionRef.open([]);
        } else if (this.form.holderType == 4) {
          this.$refs.customerSelectionRef.open([]);
        }
      },
      open(row) {
        this.$refs.form && this.$refs.form.clearValidate();
        this.dialogVisible = true;
        if (row) {
          this.title = '修改';
          this.getInfo(row.id);
        } else {
          this.title = '新增';
        }
      },
      async getOrderCode() {
        const data = await getCode('license_code');
        this.$set(this.form, 'code', data);
      },

      async getInfo(id) {
        const data = await getPhotoInfo(id);
        this.form = {
          ...data,
          type: data.type + '',
          date: [data.validityStartTime, data.validityEndTime],
          holderType: data.holderType || '1'
        };

        this.$refs.productTableRef.putTableValue(data.categorys || []);
      },

      close() {
        this.dialogVisible = false;
        // this.$refs.form.resetFields()
        this.form = { defaultForm };
        this.$refs.productTableRef.initData();
      },

      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          if (this.form.date?.length) {
            this.form.validityStartTime = this.form.date[0];
            this.form.validityEndTime = this.form.date[1];
          }

          const data = {
            ...this.form
          };
          delete data.date;
          let productTable = this.$refs.productTableRef.getTableValue();
          data.categorys = productTable || [];
          saveOrEdit(data)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.dialogVisible = false;
              this.$emit('success');
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },

      //切换持证人类型
      holderTypeChange(e) {
        if (e === 2) {
          this.getCompanyData();
        }
        this.form.holder = '';
        this.form.holderId = '';
        this.form.type = '';
      },

      //查询公司分类
      async getCompanyData() {
        let list = await listOrganizations();
        list = list.filter((el) => el.type == 20);
        this.companyData = this.$util.toTreeData({
          data: list,
          idField: 'id',
          parentIdField: 'parentId'
        });
      },

      //选择公司分类
      handleChange(val) {
        if (!val) return (this.form.processTypeName = '');
        let node = this.$refs.tree.$refs.tree.getCurrentNode();
        this.form.holderId = node.id;
      }
    }
  };
</script>

<style lang="scss">
  .el-form-item {
    margin-bottom: 20px !important;
  }
</style>
