<template>
  <div>
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      :validate-form="validForm"
      :class="$style.mainForm"
    >
      <template v-slot:form="{ model, fields }">
        <table>
          <tr>
            <td style="border: none">
              <audit-advanced-group
                :expand="planExpand"
                :expand-str="'planExpand'"
                :group-label="'基本信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="planExpand">
          <tr>
            <!-- 整改名称 -->
            <sd-form-item-td name="rectName" />
            <!-- 整改要求编号 -->
            <sd-form-item-td name="rectCode">
              <template v-slot:read-and-edit>
                {{ model.rectCode }}
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 整改计划反馈截止日期 -->
            <td class="ant-form-item-label ant-form-item-label">
              <label
                title="整改计划反馈截止日期"
                :class="fields.feedbackDate.required ? 'ant-form-item-required' : ''"
              >
                整改计划反馈<br />{{ '截\u2002止\u2003日\u2002期' }}
              </label>
            </td>
            <sd-form-item-td
              name="feedbackDate"
              :colspan="3"
              :label="'整改计划反馈截止日期'"
              :label-td-attrs="{ hidden: true }"
            >
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 附件 -->
            <sd-form-item-td name="attachment" :colspan="3" />
          </tr>
          <tr>
            <!-- 报告内容 -->
            <sd-form-item-td name="rectRequire" :colspan="3">
              <a-textarea v-model="model.rectRequire" :auto-size="{ maxRows: 3, minRows: 3 }" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 创建人 -->
            <sd-form-item-td name="creatorName" />
            <!-- 创建日期 -->
            <sd-form-item-td name="creationTime" />
          </tr>
        </table>

        <table>
          <tr
            ><td :colspan="4">
              <sd-form-item name="icRequireDefectEntity" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="listExpand"
                    :expand-str="'listExpand'"
                    group-label="缺陷列表"
                    @changedClick="changedClick"
                  >
                    <template>
                      <template>
                        <div :class="$style.wrapper">
                          <div v-show="listExpand && editable" :class="$style.btnselect">
                            <a-button
                              type="link"
                              :class="$style.batchselectFirst"
                              @click="rectSelect"
                            >
                              <a-icon type="check-circle" :theme="'filled'" />
                              选择缺陷
                            </a-button>
                            <a-button
                              :disabled="btnDisabled"
                              type="link"
                              :class="$style.batchselectThree"
                              @click="selectUser('lxr')"
                            >
                              <a-icon type="check-circle" :theme="'filled'" />
                              设置整改联系人
                            </a-button>
                            <a-button
                              :disabled="btnDisabled"
                              type="link"
                              :class="$style.batchselectSecond"
                              @click="selectUser('gzr')"
                            >
                              <a-icon type="check-circle" :theme="'filled'" />
                              设置整改跟踪人
                            </a-button>
                          </div>
                        </div>
                      </template>
                      <xm-child-table
                        :key="infoKey"
                        ref="infoData"
                        v-model="model.icRequireDefectEntity"
                        :class="$style.deptPlanChild"
                        :label="null"
                        :read-only="!editable"
                        :addbuttonvisiable="false"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                            },
                          ].concat(Array.from(fields.icRequireDefectEntity.attr.dync))
                        "
                        :columns="defectColumns"
                        :flagpage="true"
                        @onSelectChange="onSelectChange"
                        @deleted="deletedInfoData"
                      >
                        <!-- 流程名称 -->
                        <template v-slot:prcName_xm="{ text, record, field, value }">
                          {{ text }}
                        </template>
                        <!-- 控制点名称 -->
                        <template v-slot:measureName_xm="{ text, record, field, value }">
                          {{ text }}
                        </template>
                        <!-- 控制点编号 -->
                        <template v-slot:measureCode_xm="{ text, record, field, value }">
                          {{ text }}
                        </template>
                        <!-- 测试结果 -->
                        <template v-slot:testResult_xm="{ text, record, field, value }">
                          {{ text }}
                        </template>
                        <!-- 缺陷类型 -->
                        <template v-slot:defectType_xm="{ text, record, field, value }">
                          {{ text }}
                        </template>
                        <!-- 缺陷等级 -->
                        <template v-slot:defectLevel_xm="{ text, record, field, value }">
                          {{ text }}
                        </template>
                        <!-- 整改测试人 -->
                        <template v-slot:rectContactName_xm="{ text, record, field, value }">
                          {{ text }}
                        </template>
                        <!-- 整改跟踪人 -->
                        <template v-slot:rectTrackerName_xm="{ text, record, field, value }">
                          {{ text }}
                        </template>
                      </xm-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item>
            </td>
          </tr>
        </table>
      </template>
    </sd-webflow>
    <!-- 选择人员组件 -->
    <div v-show="false">
      <sd-user-picker ref="userSelect" :single="true" :read-only="false" @change="userChange" />
    </div>
    <a-modal
      :destroy-on-close="true"
      title="请选择"
      width="1500px"
      :visible="rectVisible"
      dialog-class="rectListModal"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <iam-ic-defect-statement-list ref="rectList"></iam-ic-defect-statement-list>
    </a-modal>
    <!-- 重复提示 -->
    <a-modal
      width="30%"
      :visible="modalVisible"
      title="存在重复数据"
      @ok="modalHandleOk"
      @cancel="modalHandleOk"
    >
      <template v-slot:footer>
        <a-button key="submit" type="primary" @click="modalHandleOk">确定</a-button>
      </template>
      <p v-html="modalInfoHtml"></p>
    </a-modal>
  </div>
</template>

<script>
import { message } from '@/common/one-ui'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import iamIcDefectStatementList from './iam-ic-defect-statement-list.vue'
import IamIcRectifyRequireServices from './iam-ic-rectify-require-service'
import components from './_import-components/iam-ic-rectify-require-form-import'
export default {
  name: 'IamIcRectifyRequireForm',
  metaInfo: {
    title: '整改要求',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    iamIcDefectStatementList,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      selectKeys: [],
      btnDisabled: true,
      modalVisible: false,
      modalInfoHtml: '',
      selectDataId: [], // 已选择缺陷ID
      userType: null,
      infoKey: 0,
      rectVisible: false, // 缺陷清单列表显示
      planExpand: true,
      listExpand: true,
      defectColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'prcName',
          title: '流程名称',
          width: '120px',
        },
        { dataIndex: 'measureName', title: '控制点名称' },
        { dataIndex: 'measureCode', title: '控制点编号' },
        { dataIndex: 'testResult', title: '测试结果' },
        { dataIndex: 'defectType', title: '缺陷类型' },
        { dataIndex: 'defectLevel', title: '缺陷等级' },
        { dataIndex: 'rectContactName', title: '整改联系人' },
        { dataIndex: 'rectTrackerName', title: '整改跟踪人' },
        { dataIndex: 'rectContactId', sdHidden: true },
        { dataIndex: 'rectContactAccount', sdHidden: true },
        { dataIndex: 'rectTrackerId', sdHidden: true },
        { dataIndex: 'rectTrackerAccount', sdHidden: true },
        { dataIndex: 'defectListId', sdHidden: true },
        { dataIndex: 'evaluationName', sdHidden: true },
        { dataIndex: 'liabilityOrgId', sdHidden: true },
        { dataIndex: 'liabilityOrgCode', sdHidden: true },
        { dataIndex: 'liabilityOrgName', sdHidden: true },
        { dataIndex: 'rectTrackerOpt', sdHidden: true },
        { dataIndex: 'rectContactOpt', sdHidden: true },
        { dataIndex: 'entryMethod', sdHidden: true },
      ],
    }
  },
  watch: {
    selectKeys(val) {
      if (val.length !== 0) {
        this.btnDisabled = false
      } else {
        this.btnDisabled = true
      }
    },
  },
  mounted() {},
  methods: {
    // 缺陷列表选择项
    onSelectChange(keys) {
      this.selectKeys = keys
    },
    // 选择缺陷
    rectSelect() {
      // 选择缺陷
      this.rectVisible = true
    },
    // 删除数据， 重新获取id
    deletedInfoData() {
      this.selectDataId = []
      let dataList = this.$refs.flow.getFieldValue('icRequireDefectEntity')
      if (!dataList) dataList = []
      dataList.forEach((item) => {
        this.selectDataId.push(item.defectListId)
      })
    },
    // 选择确认方法
    handleOk() {
      let dataList = this.$refs.flow.getFieldValue('icRequireDefectEntity')
      if (!dataList) dataList = []
      const titleList = []
      const selectRows = this.$refs.rectList.$refs.icDefectStatementList.getSelectedRows()
      selectRows.forEach((item) => {
        const info = {}
        info.prcName = item.prcName
        info.evaluationName = item.evaluationName
        info.defectListId = item.id
        info.measureName = item.measureName
        info.measureCode = item.measureCode
        info.defectType = item.defectType
        info.defectLevel = item.defectLevel
        info.testResult = item.testResult
        info.liabilityOrgId = item.liabilityOrgId
        info.liabilityOrgCode = item.liabilityOrgCode
        info.liabilityOrgName = item.liabilityOrgName
        info.controOrgId = item.controOrgId
        info.controOrgCode = item.controOrgCode
        info.controOrgName = item.controOrgName
        info.entryMethod = item.entryMethod
        // 重复数据不进行添加
        if (this.selectDataId.indexOf(item.id) === -1) {
          this.selectDataId.push(item.id)
          dataList.push(info)
        } else {
          titleList.push('流程名称：' + item.prcName + '，控制点名称：' + item.measureName + '<br>')
        }
      })
      if (titleList.length > 0) {
        this.modalInfoHtml = titleList.join('') + '已存在，请勿添加重复数据'
        this.modalVisible = true
      }
      this.$refs.flow.setFieldValue('icRequireDefectEntity', dataList)
      this.$refs.infoData.fnupdate(dataList)
      // 最后隐藏列表
      this.rectVisible = false
    },
    // 选择取消方法
    handleCancel() {
      this.rectVisible = false
    },
    modalHandleOk() {
      this.modalVisible = false
    },
    // 选择整改联系人和跟踪人
    selectUser(type) {
      const ids = this.$refs.infoData.selectedRowKeys
      if (ids.length === 0) {
        message.info('请选择缺陷列表数据', 1)
        return false
      }
      this.userType = type
      this.$refs.userSelect.openPicker()
    },
    // 人员选择变化时
    userChange(values) {
      const ids = this.$refs.infoData.selectedRowKeys
      const listVal = this.$refs.infoData.value
      const userObj = values[0]
      for (const index in ids) {
        if (this.userType === 'lxr') {
          listVal[ids[index]].rectContactName = userObj.name
          listVal[ids[index]].rectContactAccount = userObj.code
          listVal[ids[index]].rectContactOpt = JSON.stringify(values)
        }
        if (this.userType === 'gzr') {
          listVal[ids[index]].rectTrackerName = userObj.name
          listVal[ids[index]].rectTrackerAccount = userObj.code
          listVal[ids[index]].rectTrackerOpt = JSON.stringify(values)
        }
      }

      this.$refs.flow.setFieldValue('icRequireDefectEntity', listVal)
      this.$refs.infoData.fnupdate(listVal)
    },
    // 获取用户姓名
    getUserName(jsonStr) {
      if (!jsonStr) return ''
      return jsonStr[0].name
    },
    selectclick() {
      return false
    },
    initData() {
      // 如果不是起草，则直接退出，不需要获取计划信息了
      if (!this.planId | this.isIni) return false
      this.isIni = true
      // 生成标题
      IamIcRectifyRequireServices.getPlanInfo(this.planId).then((res) => {
        if (res.status === 200) {
          const planTitle = res.data.pageFormData.pageFieldInfos.find((item) => {
            return item.name === 'evaluationName'
          }).value
          this.$refs.flow.setFieldValue('reportName', planTitle + '的内控评价报告')
        }
      })
      // 获取所有被评价单位
      IamIcRectifyRequireServices.getDvaluationDept(parseFloat(this.planId)).then((res) => {
        if (res.status === 200) {
          this.$refs.flow.setFieldValue('evaluatedUnitOpt', res.data)
        }
      })
      return false
    },
    actionBtnClick(evt, { button, FlowData }) {
      if (button.fakeId === 'save' || button.fakeId === 'workflow-push') {
      }
    },
    // 自定义校验
    validForm() {
      // 待办标题赋值
      this.$refs.flow.setFieldValue('title', this.$refs.flow.getFieldValue('rectName'))
      // 获取环节号
      const flowNum = this.$refs.flow.flowData.attrs.stepN
      // 起草环节才校验 校验是否选择了缺陷
      if (flowNum === 0) {
        let dataList = this.$refs.flow.getFieldValue('icRequireDefectEntity')
        if (!dataList) dataList = []
        if (dataList.length === 0) {
          message.info('请添加缺陷列表数据', 1)
          return Promise.resolve(false)
        } else {
          let submit = true
          dataList.forEach((item) => {
            if (!item.rectTrackerName | !item.rectContactName) {
              submit = false
            }
          })
          // 判断是否可以提交
          if (submit) {
            return Promise.resolve(true)
          } else {
            message.info('请设置缺陷列表内整改联系人以及整改跟踪人', 1)
            return Promise.resolve(false)
          }
        }
      } else {
        return Promise.resolve(true)
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
:global(.modal-info-rectify-require) {
  :global(div.ant-modal) {
    width: 50% !important;
  }
}
.main-form {
  :global(.header_xm-child-table_product) {
    right: 340px;
    z-index: 101;
  }
  :global(.ant-calendar-picker) {
    width: 100%;
  }
  .btnselect {
    position: relative;
    top: 4px;
    float: right;
    z-index: 100;
    .batchselect-first {
      margin-right: 100px !important;
    }
    .batchselect-second {
      z-index: 100;
    }
    .batchselect-three {
      z-index: 100;
    }
  }
}
:global(.rectListModal) {
  :global(.ant-modal-body) {
    overflow-x: hidden;
  }
}
</style>
