<template>
  <a-card>
    <SdDataTable
      ref="sddataTable"
      :data-url="pageId"
      :columns="columns"
      :actions="actions"
      show-selection
      :process-req="processReq"
      :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>
    </SdDataTable>
    <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">
          <a-input v-if="isEditType" v-model="formData.unitName" :disabled="true" />
          <SdGroupPicker
            v-else
            ref="cRelSelect"
            v-model="companyUnit"
            :single="true"
            :read-only="false"
            :root-node="userNodeTree"
            @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, Modal } from 'ant-design-vue'
import SdDataTable from '@/common/components/sd-data-table.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'
import { getUserInfo } from '@/common/store-mixin'

export default {
  name: 'AuditBindPeople',
  metaInfo: {
    title: '关联人员',
  },
  components: {
    SdDataTable,
    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' },
          // 调用接口
          {
            validator: (rule, value, callback) => {
              if (this.isEditType) {
                callback()
                return
              }
              const params = {
                domainId: this.formData.domainId,
                unitId: this.formData.unitId,
              }
              auditMaintainService.checkBind(params).then((res) => {
                if (res.data) {
                  callback()
                } else {
                  callback(new Error('当前公司已绑定' + this.formData.domainName))
                }
              })
            },
            trigger: 'change',
          },
        ],
        reformUser: [{ required: true, message: '请选择整改人', trigger: 'blur' }],
        checker: [{ required: true, message: '请选择初审人', trigger: 'blur' }],
        reviewer: [{ required: true, message: '请选择复审人', trigger: 'blur' }],
      },
      formId: 'iamModelDomainUserRel',
      pageId: 'api/xcoa-mobile/v1/model-domain-user/getQueryList',
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        // 领域编号 ，领域名称 公司名称 创建时间
        // 不设置宽度
        {
          title: '领域编号',
          dataIndex: 'domainId',
        },
        {
          title: '领域名称',
          dataIndex: 'domainName',
        },
        // 组织机构
        {
          title: '组织编码',
          dataIndex: 'unitCode',
        },
        {
          title: '公司名称',
          dataIndex: 'unitName',
        },

        {
          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: '删除',
          permission: null,
          // id: 'delete',
          // type: TableActionTypes.primary,
          callback: this.deleteAreas, // 删除按钮，不需要回调，会自动处理（对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: '',
      },
      isEditType: false,
      formDetail: null,
      userNodeTree: [],
    }
  },
  computed: {
    formItemLayout() {
      return {
        layout: 'horizontal',
        labelCol: { span: 4 },
        wrapperCol: { span: 18 },
      }
    },
  },
  created() {
    this.initUserCompanyRole()
  },
  methods: {
    // 删除领域绑定
    deleteAreas() {
      const ids = this.$refs.sddataTable.getSelectedRowKeys()
      if (ids.length === 0) {
        message.error('请选择要删除的数据')
        return
      }
      const idsStr = ids.join(',')
      Modal.confirm({
        title: '提示',
        content: '删除后将无法恢复，是否确认删除？',
        onOk: () => {
          auditMaintainService.deleteArea(idsStr).then((res) => {
            message.success('删除成功')
            this.$refs.sddataTable.refresh()
          })
        },
      })
    },
    // 初始化， 获取当前人群的权限，
    initUserCompanyRole() {
      auditMaintainService.getGroup().then((res) => {
        // 100000和100001
        const roleCompany = ['100000', '100001']
        this.userNodeTree = res.data.map((item) => {
          return {
            code: item.id,
            name: item.name,
            type: 'Group',
          }
        })
        if (roleCompany.includes(res.data.code)) {
          this.userNodeTree = []
        }
      })
    },
    // 编辑
    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
    },
    processReq(data) {
      data.data.expressions = data.data.expressions.map((val) => {
        if (val.name === 'domainId') {
          return val
        } else {
          return val.expressionsValue[0]
        }
      })
      data.data.expressions.push(...this.expressions)
      // 如果长度大于1，说明是高级查询
      return data
    },
    // 保存
    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
      // 清除提示
      this.$refs.ruleFormData.clearValidate()
    },
    onRowLink(id = null) {
      this.visible = true
      this.isEditType = id !== null
      const data = { id }
      // 如果id不为空，说明是编辑
      // 则id + ''
      if (this.isEditType) {
        data.id = 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>
