<template>
  <a-card>
    <SdDataTableEx
      ref="sddataTable"
      :form-id="formId"
      :page-id="pageId"
      :columns="columns"
      :actions="actions"
      show-selection
      :filter-expressions="expressions"
      :search-fields="['unitName']"
      :show-advance-query="true"
    >
      <!-- 插槽放置表格内容 -->
      <!-- 编辑 -->
      <template slot="edit" slot-scope="text, record">
        <a-button type="link" @click="onRowLink(record.id)">编辑</a-button>
      </template>
    </SdDataTableEx>
    <a-modal title="人员绑定" :visible="visible" @ok="handleOk" @cancel="handleCancel">
      <a-form-model
        ref="ruleFormData"
        layout="horizontal"
        :model="formData"
        :rules="rules"
        v-bind="formItemLayout"
      >
        <a-form-model-item label="领域名称" prop="domainName">
          <a-input v-model="formData.domainName" :disabled="true"></a-input>
        </a-form-model-item>
        <!-- 公司  -->
        <a-form-model-item label="单位" prop="unitName">
          <SdGroupPicker
            ref="cRelSelect"
            v-model="companyUnit"
            :single="true"
            :read-only="false"
            @change="changecompany"
          />
        </a-form-model-item>
        <!-- 整改人 -->
        <a-form-model-item label="整改人" prop="reformUser">
          <a-input v-if="isDisabled" :disabled="true" placeholder="请先选择单位"></a-input>

          <sd-user-picker
            v-else
            ref="peopleRelSelect"
            v-model="reformUserValue"
            :single="false"
            :read-only="false"
            :root-node="rootNode"
            @change="reformUserChange"
          />
        </a-form-model-item>
        <!-- 初审人 -->
        <a-form-model-item label="初审人" prop="checker">
          <a-input v-if="isDisabled" :disabled="true" placeholder="请先选择单位"></a-input>

          <sd-user-picker
            v-else
            ref="peopleRelSelect"
            v-model="checkerValue"
            :single="false"
            :read-only="false"
            :root-node="rootNode"
            @change="checkerValueChange"
          />
        </a-form-model-item>
        <!-- 复审人 -->
        <a-form-model-item label="复审人" prop="reviewer">
          <a-input v-if="isDisabled" :disabled="true" placeholder="请先选择单位"></a-input>
          <sd-user-picker
            v-else
            ref="peopleRelSelect"
            v-model="reviewerValue"
            :single="false"
            :read-only="false"
            :root-node="rootNode"
            @change="reviewerValueChange"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import components from './_import-components/audit-bind-people-import'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import auditMaintainService from './audit-maintain-service'
import { message } from 'ant-design-vue'
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import SdGroupPicker from '@/common/components/sd-group-picker.vue'
import auditModelService from '../model/audit-model-service'
export default {
  name: 'AuditBindPeople',
  metaInfo: {
    title: '关联人员',
  },
  components: {
    SdDataTableEx,
    sdUserPicker,
    SdGroupPicker,
    ...components,
  },
  data() {
    return {
      expressions: [
        {
          dataType: 'str',
          name: 'domainId',
          op: 'eq',
          stringValue: this.$route.query.domainId,
        },
      ],
      rules: {
        domainName: [{ required: true, message: '请选择领域名称', trigger: 'blur' }],
        // 所有选项不能为空
        unitName: [{ required: true, message: '请选择单位', trigger: 'blur' }],
        reformUser: [{ required: true, message: '请选择整改人', trigger: 'blur' }],
        checker: [{ required: true, message: '请选择初审人', trigger: 'blur' }],
        reviewer: [{ required: true, message: '请选择复审人', trigger: 'blur' }],
      },
      formId: 'iamModelDomainUserRel',
      pageId: 'audit/maintain/iamModelDomainUserRel',
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        // 领域编号 ，领域名称 公司名称 创建时间
        // 不设置宽度
        {
          title: '领域编号',
          dataIndex: 'domainId',
        },
        {
          title: '领域名称',
          dataIndex: 'domainName',
        },
        {
          title: '公司名称',
          dataIndex: 'unitName',
        },
        {
          dataIndex: 'unitCode',
          sdHidden: true,
        },
        {
          dataIndex: 'unitId',
          sdHidden: true,
        },
        {
          title: '整改人',
          dataIndex: 'reformUser',
        },
        {
          dataIndex: 'reformUserAccount',
          sdHidden: true,
        },
        {
          title: '初审人',
          dataIndex: 'checker',
        },
        { dataIndex: 'checkerAccount', sdHidden: true },
        {
          title: '复审人',
          dataIndex: 'reviewer',
        },
        { dataIndex: 'reviewerAccount', sdHidden: true },

        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
        },
        {
          // 操作
          title: '操作',
          dataIndex: 'id',
          scopedSlots: { customRender: 'edit' },
        },
      ],
      actions: [
        {
          label: '新增',
          permission: null,
          type: TableActionTypes.primary,
          callback: this.onRowLink,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
      ],

      // 人员选择器
      reformUserValue: [],
      checkerValue: [],
      reviewerValue: [],
      rootNode: {},
      companyUnit: null,
      isDisabled: true,
      flag: true,
      visible: false,
      formData: {
        domainId: '',
        domainName: '',
        unitName: '',
        unitId: '',
        reformUser: '',
        reformUserAccount: '',
        checker: '',
        checkerAccount: '',
        reviewer: '',
        reviewerAccount: '',
      },
      formDetail: null,
    }
  },
  computed: {
    formItemLayout() {
      return {
        layout: 'horizontal',
        labelCol: { span: 4 },
        wrapperCol: { span: 18 },
      }
    },
  },
  created() {},
  methods: {
    // 编辑
    editDetail(record) {
      const ground = {
        name: record.unitName,
        code: record.unitId,
        type: 'Group',
      }
      this.companyUnit = [ground]
      this.rootNode = ground
      const checkerNames = record.checker.split(',')
      const checkerCodes = record.checkerAccount.split(',')
      this.checkerValue = checkerNames.map((item, index) => {
        return {
          name: item,
          code: checkerCodes[index],
          type: 'User',
        }
      })
      const reformUserNames = record.reformUser.split(',')
      const reformUserCodes = record.reformUserAccount.split(',')
      this.reformUserValue = reformUserNames.map((item, index) => {
        return {
          name: item,
          code: reformUserCodes[index],
          type: 'User',
        }
      })
      const reviewerNames = record.reviewer.split(',')
      const reviewerCodes = record.reviewerAccount.split(',')
      this.reviewerValue = reviewerNames.map((item, index) => {
        return {
          name: item,
          code: reviewerCodes[index],
          type: 'User',
        }
      })
      this.isDisabled = false
      this.visible = true
    },
    // 保存
    handleOk() {
      this.$refs.ruleFormData.validate((valid) => {
        if (valid) {
          // const data = {
          //   eventId: 'save',
          //   inputs: [],
          //   pageFlowId: this.formDetail.attrs.pageflowId,
          //   pagePath: this.formDetail.attrs.pagePath,
          // }
          // const objList = []
          // Object.keys(this.formData).map((item) => {
          //   objList.push({
          //     name: item,
          //     value: this.formData[item],
          //   })
          // })
          // data.inputs = objList
          // auditModelService.handleData(data).then((res) => {
          //   message.success('保存成功')
          //   this.$refs.sddataTable.refresh()
          //   this.handleCancel()
          // })
          const data = this.formData
          auditMaintainService.butchBindPeople(data).then((res) => {
            message.success('保存成功')
            this.$refs.sddataTable.refresh()
            this.$refs.sddataTable.clearSelection()
            this.handleCancel()
          })
        }
      })
    },
    handleCancel() {
      this.isDisabled = true
      this.reformUserValue = []
      this.checkerValue = []
      this.reviewerValue = []
      this.companyUnit = []
      this.formData.id = null
      this.visible = false
    },
    onRowLink(id = null) {
      this.visible = true
      const data = { id }
      auditModelService.getHandleData(data).then((res) => {
        this.formDetail = res.data
        const obj = {}
        res.data.pageFormData.pageFieldInfos.map((item) => {
          obj[item.name] = item.value
        })
        this.formData = obj
        if (id !== null) {
          this.rootNode = {
            code: obj.unitId,
            name: obj.unitName,
          }
          this.editDetail(obj)
        }
        this.getAreaDetail()
      })
    },
    // 人员变化事件
    reformUserChange(val) {
      this.reformUserValue = val
      // 序列化人员信息使用,分隔
      const reformUser = val.map((item) => item.name).join(',')
      const reformUserAccount = val.map((item) => item.code).join(',')
      this.formData.reformUser = reformUser
      this.formData.reformUserAccount = reformUserAccount
    },
    checkerValueChange(val) {
      this.checkerValue = val
      const checker = val.map((item) => item.name).join(',')
      const checkerAccount = val.map((item) => item.code).join(',')
      this.formData.checker = checker
      this.formData.checkerAccount = checkerAccount
    },
    reviewerValueChange(val) {
      this.reviewerValue = val
      const reviewer = val.map((item) => item.name).join(',')
      const reviewerAccount = val.map((item) => item.code).join(',')
      this.formData.reviewer = reviewer
      this.formData.reviewerAccount = reviewerAccount
    },
    // 单位变化事件
    changecompany(val) {
      const unitId = val.map((item) => item.code).join(',')
      const unitName = val.map((item) => item.name).join(',')
      this.formData.unitName = unitName
      this.formData.unitId = unitId
      // 清空人员
      this.reviewerValueChange([])
      this.checkerValueChange([])
      this.reformUserChange([])
      if (val.length > 0) {
        this.isDisabled = false
        this.rootNode = val
      } else {
        this.isDisabled = true
      }
    },
    showFormModal(id = null) {
      this.$refs.sddataTable.showDetailModal(id, this.pageId)
    },
    // 获取人员列表
    getAreaDetail() {
      if (!this.$route.query.domainId) {
        message.error('请先选择领域')
        // 关闭当前页
        window.close()
        return
      }

      auditMaintainService.getAreaDetail(this.$route.query.domainId).then((res) => {
        const obj = {}
        res.data.pageFormData.pageFieldInfos.map((item) => {
          obj[item.name] = item.value
          return obj
        })
        //         domainId
        // domainName
        this.flag = false
        this.formData.domainId = obj.id
        this.formData.domainName = obj.name
      })
      return true
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
