<template>
  <ele-modal custom-class="ele-dialog-form long-dialog-form"
             :centered="true" :visible.sync="certificateQualificationsDialogFlag" :title="title"
             append-to-body
             :close-on-click-modal="false" width="80%" :before-close="cancel">

    <el-form ref="form" :model="form">
      <headerTitle title="基本信息"/>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label-width="50px" label="名称" prop="name"
                        :rules=" {required: true, message: '请输入',trigger: 'blur' }">
            <el-input v-model="form.name" :disabled="type=='view'" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="50px" label="备注">
            <el-input type="textarea" v-model="form.remark" :disabled="type=='view'" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <headerTitle title="资质信息"/>
      <ele-pro-table ref="linkTable" :columns="columns" :datasource="form.detailList" :toolkit="[]" height="350px"
                     :need-page="false">
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>

          <el-button v-if="type!=='view'" type="primary" @click="handleAdd">添加</el-button>
        </template>
        <template v-slot:type="scope">
          <el-form-item :prop="'detailList.' + scope.$index + '.type'" :rules="{
            required: true,
            message: '',
            trigger: 'change'
          }">
            <el-select v-if="type!=='view'" v-model="scope.row.type" clearable
                       @change="(val)=>handleChangeType(val,scope.row)">
              <el-option :disabled="disabledToType(scope.row).includes(item.dictCode)"
                         v-for="item in dictList" :value="item.dictCode"
                         :label="item.dictValue"></el-option>
            </el-select>

            <span v-else>{{ scope.row.name }}</span>
            <!--            <DictSelection v-show="false" clearable dictName="客户/供应商资质类型" v-model="scope.row.type"-->
            <!--                           @itemChange="(val)=>handleChangeType(val,scope.row)"></DictSelection>-->
          </el-form-item>

        </template>
        <template v-slot:num="scope">
          <el-form-item :prop="'detailList.' + scope.$index + '.num'" :rules="{
            required: true,
            message: '',
            trigger: 'blur'
          }">
            <el-input v-model="scope.row.num" :disabled="type=='view'" clearable></el-input>
          </el-form-item>

        </template>
        <template v-slot:scope="scope">
          <el-form-item :prop="'detailList.' + scope.$index + '.scope'">
            <el-input type="textarea" v-model="scope.row.scope" :disabled="type=='view'" clearable></el-input>
          </el-form-item>
        </template>
        <template v-slot:validityPeriodStart="scope">
          <el-form-item inline-message :prop="'detailList.' + scope.$index + '.validityPeriodStart'" :rules="{
            required: true,
            message: '',
            trigger: 'change'

          }">
            <el-date-picker
              :disabled="type=='view'"
              v-model="scope.row.validityPeriodStart"
              type="date"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>

        </template>
        <template v-slot:validityPeriodEnd="scope">
          <el-form-item :prop="'detailList.' + scope.$index + '.validityPeriodEnd'" :rules="{
            required: true,
            validator: validateEndDate(scope.row,scope.$index),
            trigger: ['blur','change']
          }">
            <el-date-picker
              :disabled="type=='view'"
              v-model="scope.row.validityPeriodEnd"
              type="date"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>

        </template>
        <template v-slot:notifyUserName="scope">
          <el-form-item :prop="'detailList.' + scope.$index + '.notifyUserName'" :rules="{
            required: true,
            message: '',
            trigger: ['blur','change']

          }">
            <el-input
              :disabled="type=='view'"
              @click.native="openStaffSelection(scope.$index)"
              v-model="scope.row.notifyUserName"
              placeholder="请选择"
            ></el-input>
          </el-form-item>

        </template>
        <template v-slot:files="scope">
          <el-form-item :prop="'detailList.' + scope.$index + '.files'" :rules="{
            required: true,
            message: '',
            trigger: ['change','blur']
          }">
            <fileUpload
              v-if="type!=='view'"
              v-model="scope.row.files"
              module="main"
              :showLib="false"
              :limit="10"/>
            <div v-else>
              <el-link
                v-for="link in scope.row.files"
                :key="link.id"
                type="primary"
                :underline="false"
                @click="downloadFile(link)">
                {{ link.name }}
              </el-link>
            </div>
          </el-form-item>

        </template>
        <template v-slot:remark="scope">
          <el-form-item :prop="'detailList.' + scope.$index + '.remark'">
            <el-input type="textarea" :disabled="type=='view'" v-model="scope.row.remark"></el-input>
          </el-form-item>
        </template>
        <template v-slot:status="scope">
          <el-form-item :prop="'detailList.' + scope.$index + '.status'">
            <el-tag v-if="scope.row.status" :type="statusTagTypeList[scope.row.status]">{{statusList[scope.row.status]}}</el-tag>
          </el-form-item>
        </template>
        <template v-slot:isRequired="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
        <template v-slot:action="{ row, $index }">
          <el-popconfirm
            class="ele-action"
            title="确定要删除该信息吗？"
            @confirm="handleRemove($index)">
            <template v-slot:reference>
              <el-link
                v-if="type!=='view'"
                type="danger"
                :underline="false"
                icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>

      </ele-pro-table>

    </el-form>
    <div slot="footer">
      <el-button type="primary" v-if="type!=='view'" @click="handleSave(false)">保存</el-button>
      <!--      <el-button type="primary" v-if="type!=='view'" plan @click="handleSave(true)">提交</el-button>-->
      <el-button @click="cancel">返回</el-button>
    </div>
    <staffSelection
      ref="staffSelection"
      @confirm="confirmStaffSelection"
    ></staffSelection>

  </ele-modal>
</template>
<script>
import FileUpload from "@/components/upload/fileUpload.vue";
import staffSelection from "@/components/staffSelection/staffSelection.vue";
import {
  contactQcPackDetailAPI,
  contactQcPackSaveAPI,
  contactQcPackUpdateAPI,
  contactQcSubmit
} from "@/api/bpm/components/supplierManage/contact";
import {getFile} from "@/api/system/file";
import {mapActions, mapGetters} from "vuex";
import dictEnum from "@/enum/dict";

export default {
  name: "certificateQualificationsDialog",
  components: {FileUpload, staffSelection},
  props: {
    certificateQualificationsDialogFlag: Boolean,
    contactId: String,
    typeInfo: String,
  },
  computed: {
    ...mapGetters(['dict']),
    dictList() {
      return this.dict[dictEnum['客户/供应商资质类型']] || [];
    },
    disabledToType() {
      return (row) => {
        let list = this.form.detailList.map(item => item.type)
        let dictCodeList = this.dictList.map(item => item.dictCode)
        let intersectionList = list.filter((v) => dictCodeList.indexOf(v) > -1)
        intersectionList = intersectionList.filter(v => row.type !== v)
        return intersectionList
      }
    },
  },
  created() {
    this.requestDict('客户/供应商资质类型');
  },
  data() {
    return {
      title: '',
      type: '',
      defaultData: {
        files: [],
        name: "",
        notifyUserId: "",
        notifyUserName: "",
        num: "",
        remark: "",
        scope: "",
        type: "",
        validityPeriodEnd: "",
        validityPeriodStart: ""
      },
      form: {
        detailList: [],
        contactId: '',
        name: '',
        remark: '',

      },
      curIndex: null,
      columns: [
        {
          type: 'index',
          width: 55,
          align: 'center'
        },
        {
          label: '名称',
          prop: 'type',
          slot: 'type',
          headerSlot: 'isRequired',
          minWidth: 120,
          align: 'center'
        },
        {
          label: '编号',
          prop: 'num',
          slot: 'num',
          headerSlot: 'isRequired',
          minWidth: 120,
          align: 'center'
        },
        {
          label: '许可/经营范围',
          prop: 'scope',
          slot: 'scope',
          minWidth: 140,
          align: 'center'
        },
        {
          label: '有效期起始日期',
          prop: 'validityPeriodStart',
          slot: 'validityPeriodStart',
          headerSlot: 'isRequired',
          minWidth: 140,
          align: 'center'
        },
        {
          label: '有效期截止日期',
          prop: 'validityPeriodEnd',
          slot: 'validityPeriodEnd',
          headerSlot: 'isRequired',
          minWidth: 140,
          align: 'center'
        },
        {
          label: '通知人',
          prop: 'notifyUserName',
          slot: 'notifyUserName',
          headerSlot: 'isRequired',
          minWidth: 140,
          align: 'center'
        },
        {
          label: '附件',
          prop: 'files',
          slot: 'files',
          headerSlot: 'isRequired',
          minWidth: 140
        },
        {
          label: '备注',
          prop: 'remark',
          slot: 'remark',
          action: 'remark',
          align: 'center'
        },
        {
          label: '状态',
          prop: 'status',
          slot: 'status',
          align: 'center',
        },
        {
          action: 'action',
          slot: 'action',
          label: '操作',
          align: 'center'
        }
      ],
      statusList : {
        10: '有效',
        20: '无效',
        30: '已过期',
      },
      statusTagTypeList : {
        10: 'success',
        20: 'info',
        30: 'danger',
      },
    }
  },
  methods: {
    ...mapActions('dict', ['requestDict']),
    //结束日期验证
    validateEndDate(row, index) {
      return (rule, value, callback) => {
        if (!value) return callback(new Error(''))
        if (
          row.validityPeriodEnd &&
          row.validityPeriodStart &&
          value < row.validityPeriodStart
        ) {
          callback(new Error('截止日期不能小于起始日期'))
        } else {
          callback()
        }
      }
    },
    //页面初始化
    init(type, row = {}) {
      this.title = type == 'add' ? '新增' : type == 'update' ? '修改' : '详情'
      this.type = type
      if (type !== 'add') {
        this.getCertificateInfo(row)
      }
    },
    async getCertificateInfo(row) {
      this.form = await contactQcPackDetailAPI(row.id)
    },
    //打开选择负责人弹窗
    openStaffSelection(index) {
      this.curIndex = index
      this.$refs.staffSelection.open([]);
    },
    //选择负责人回调
    confirmStaffSelection(data) {
      this.form.detailList[this.curIndex].notifyUserName = data.map((item) => item.name).toString();
      this.form.detailList[this.curIndex].notifyUserId = data.map((item) => item.id).toString();
    },
    //删除资质
    handleRemove(index) {
      this.form.detailList.splice(index, 1)
    },
    //新增
    handleAdd() {
      this.form.detailList.push({...this.defaultData})
    },
    //修改资质证书
    handleChangeType(val, row) {
      if (!val) return row.name = ''
      row.name = this.dictList.find(i => i.dictCode == val)?.dictValue || ''

    },
    downloadFile(file) {
      getFile({objectName: file.storePath}, file.name);
    },
    //保存/提交
    handleSave(isSub) {
      if (!this.contactId) return this.$message.success('请保存合同信息后新增资质')

      this.$refs.form.validate(async (valid) => {
        if (!valid) return this.$message.warning('有必填项未填写，请检查')
        if (!this.form.detailList.length) return this.$message.warning('至少保存一条资质信息')
        this.form.contactId = this.contactId
        let api = this.type == 'add' ? contactQcPackSaveAPI : contactQcPackUpdateAPI
        let id = await api(this.form)
        if (isSub) {
          await contactQcSubmit({businessId: id, type: this.typeInfo})
        }
        this.$message.success('保存成功')
        this.$emit('reload')
        this.cancel()
      })

    },
    //关闭弹窗
    cancel() {
      this.$emit('update:certificateQualificationsDialogFlag', false)
    },
  }

}
</script>
<style scoped lang="scss">
:deep.el-form-item {
  margin-bottom: 0
}
</style>
