<template>
  <span>
    <audit-form-top-banner
      :handel-save-form="saveForm"
      :form-data="mode"
      @handelSaveForm="saveForm"
    >
      <sd-detail-form
        ref="docform"
        page-id="audit/externalProject/iamExternalFind"
        :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
        :class="$style.form"
        @close="close(true)"
        @saved="saved"
        @sdFormReady="
          () => {
            this.sdFormReady()
          }
        "
      >
        <template v-slot="{ model, fields }">
          <table
            ><tr
              ><td style="border: none">
                <audit-advanced-group
                  :expand="basicExpand"
                  :expand-str="'basicExpand'"
                  :group-label="'基本信息'"
                  tablestyle="''"
                  @changedClick="changedClick"
                ></audit-advanced-group> </td></tr
          ></table>

          <table>
            <colgroup>
              <col style="width: 15%"/>
              <col style="width: 35%"/>
              <col style="width: 15%"/>
              <col style="width: 35%"
            /></colgroup>

            <tr v-show="false">
              <!-- <tr v-show="initParam(model)"> -->
              <!-- 项目id -->
              <sd-form-item-td :hidden="true" name="projectId" :colspan="3" />
            </tr>
            <tr v-show="basicExpand">
              <!-- 审计发现标题 -->
              <sd-form-item-td name="findTitle" :colspan="3">
                <a-input v-model="model.findTitle" />
                <!-- <a-input v-model="model.findTitle" style="width: calc(100% - 80px)" /> -->
                <!-- <span style="padding: 5px">
                  <a-button @click="showfind">选择</a-button>
                </span> -->
              </sd-form-item-td>
            </tr>
            <tr v-show="basicExpand">
              <!-- 审计发现编号 -->
              <sd-form-item-td name="findCode" />
              <!-- 被审计单位 -->
              <sd-form-item-td name="auditedUnit" />
            </tr>
            <tr v-show="false">
              <!-- 被审计单位id -->
              <sd-form-item-td :hidden="true" name="auditedUnitIds"> </sd-form-item-td>
              <sd-form-item-td :hidden="true" name="auditedUnitNames"> </sd-form-item-td>
            </tr>
            <tr v-show="basicExpand">
              <!-- 审计发现描述 -->
              <sd-form-item-td name="findDesc" :colspan="3">
                <a-textarea
                  v-model="model.findDesc"
                  :auto-size="{ minRows: 3, maxRows: 3 }"
                ></a-textarea>
              </sd-form-item-td>
            </tr>
            <tr v-show="basicExpand">
              <!-- 是否下达审计意见书 -->
              <sd-form-item-td name="giveOpinion" :label="'是否属于审计意见书问题'" />
              <!-- 问题性质 -->
              <sd-form-item-td name="problemNature">
                <a-select v-model="model.problemNature" :allow-clear="true">
                  <a-select-option
                    v-for="item in fields.problemNature.attr.selectListItem.filter((itc) =>
                      ['wt'].includes(itc.value)
                    )"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </sd-form-item-td>
            </tr>

            <tr v-show="basicExpand">
              <!-- 审计发现类别 -->
              <!-- <sd-form-item-td name="findType">
                <template v-slot:read-and-edit="{ editable }">
                  <a-input v-if="editable" v-model="findType" read-only @click="showfindcat" />
                  <span v-else>{{ JSON.parse(model.findType).text }}</span>
                  <a-input v-model="model.findType" :hidden="true" />
                </template>
              </sd-form-item-td> -->
              <!-- 审计建议类型 -->
              <!-- <sd-form-item-td name="suggestionType" /> -->
              <!-- 问题类别分类（管理职能） || this.$root.$route.query.mode="EDIT"-->
              <sd-form-item-td name="problemCategoryFunction">
                <template v-slot>
                  <a-input v-model="problemCategoryFunction" read-only @click="showfindcat" />
                  <a-input v-model="model.problemCategoryFunction" :hidden="true" />
                </template>
                <template v-slot:read>
                  {{ JSON.parse(model.problemCategoryFunction).text }}
                </template></sd-form-item-td
              >
              <!-- 是否属于零容忍事项 -->
              <sd-form-item-td name="zeroTolerate"> </sd-form-item-td>
            </tr>
            <tr v-show="basicExpand" class="iamAuditExternalProjectFindForm">
              <!-- 是否移送纪检监察线索（单移送） -->
              <sd-form-item-td name="transferClueSingle"> </sd-form-item-td>
              <!-- 是否移送纪检监察线索（双移送） -->
              <sd-form-item-td name="transferClueDouble"> </sd-form-item-td>
            </tr>
            <tr>
              <!-- 审计依据 -->
              <sd-form-item-td name="iamBasis" :colspan="3">
                <a-textarea v-model="model.iamBasis" :rows="3" />
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 审计处理意见 -->
              <!-- <sd-form-item-td name="handleSuggestion"> </sd-form-item-td> -->
              <!-- 审计处理意见 -->
              <sd-form-item-td name="handleSuggestion" :colspan="3" :label="'审计处理意见'">
                <a-textarea v-model="model.handleSuggestion" :rows="3" />
              </sd-form-item-td>
            </tr>

            <!-- <tr v-show="basicExpand"> -->
            <!-- 问题来源 -->
            <!-- <sd-form-item-td name="problemSource"> </sd-form-item-td> -->
            <!-- 问题类别分类（按部门分类） -->
            <!-- <sd-form-item-td name="problemCategoryDept"> </sd-form-item-td> -->
            <!-- </tr> -->
            <!-- <tr v-show="basicExpand"> -->
            <!-- 审计建议描述 -->
            <!-- <sd-form-item-td name="suggestion" :colspan="3">
                <a-textarea
                  v-model="model.suggestion"
                  :auto-size="{ minRows: 3, maxRows: 3 }"
                ></a-textarea>
              </sd-form-item-td>
            </tr> -->

            <!-- <tr v-show="basicExpand"> -->
            <!-- 对应审计步骤 -->
            <!-- <sd-form-item-td name="stepName">
                <a-input v-model="model.stepName" type="text" read-only @click="showstep(model)" />
              </sd-form-item-td> -->
            <!-- </tr> -->

            <!-- <tr v-show="basicExpand"> -->
            <!-- 是否金额类问题 -->
            <!-- <sd-form-item-td name="amountProblem"> </sd-form-item-td> -->
            <!-- </tr> -->
            <!-- <tr v-show="basicExpand"> -->
            <!-- 审计意见书下发时间 -->
            <!-- <sd-form-item-td name="opinionGiveTime"> </sd-form-item-td> -->
            <!-- 问题类别 -->
            <!-- <sd-form-item-td name="problemType" /> -->
            <!-- </tr> -->
            <!-- <tr v-show="basicExpand"> -->
            <!-- 是否属于重大违规问题 -->
            <!-- <sd-form-item-td name="greatProblem"> </sd-form-item-td> -->
            <!-- 重大违规问题类别 -->
            <!-- <sd-form-item-td name="greatProblemCategory"> </sd-form-item-td> -->
            <!-- </tr> -->
            <!-- <tr v-show="basicExpand"> -->

            <!-- 零容忍事项确认依据 -->
            <!-- <sd-form-item-td name="zeroTolerateBasis"> </sd-form-item-td> -->
            <!-- </tr> -->
            <!-- <tr v-show="basicExpand"> -->
            <!-- 审计依据 -->
            <!-- <sd-form-item-td name="iamBasis"> </sd-form-item-td> -->
            <!-- </tr> -->
            <!-- <tr v-show="basicExpand"> -->
            <!-- 问题责任部门 -->
            <!-- <sd-form-item-td name="responsibleDept" /> -->
            <!-- 风险评级 -->
            <!-- <sd-form-item-td name="riskLevel" /> -->
            <!-- </tr> -->
            <!-- <tr v-show="basicExpand"> -->
            <!-- 所属业务域 -->
            <!-- <sd-form-item-td name="businessProcess" /> -->
            <!-- 是否问责 -->
            <!-- <sd-form-item-td name="whetherOrderDuty" /> -->
            <!-- </tr> -->
            <!-- <tr v-show="basicExpand"> -->
            <!-- 问责要求 -->
            <!-- <sd-form-item-td name="orderDutyAsk" :colspan="3">
                <a-textarea v-model="model.orderDutyAsk" :auto-size="{ minRows: 3, maxRows: 3 }" />
              </sd-form-item-td> -->
            <!-- </tr> -->
            <tr>
              <!-- 整改责任主体-->
              <sd-form-item-td name="respUnitName" />
              <!-- 发送整改状态 -->
              <sd-form-item-td name="sendStatus" />
            </tr>
            <tr v-show="basicExpand">
              <!-- 备注 -->
              <!-- <sd-form-item-td v-if="initParam(model)" name="findRemark" :colspan="3">
                <a-textarea v-model="model.findRemark" :auto-size="{ minRows: 3, maxRows: 3 }" />
              </sd-form-item-td> -->
              <sd-form-item-td v-if="initParam(model)" name="findRemark" :colspan="3">
                <template v-slot>
                  <a-textarea
                    v-model="model.findRemark"
                    :auto-size="{ minRows: 3, maxRows: 3 }"
                  ></a-textarea>
                </template>
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 非金额类问题类别-->
              <sd-form-item-td name="notAmountType" />
            </tr>
            <tr
              ><td :colspan="4">
                <sd-form-item :label="null" name="iamExternalFindMoneyEntitys">
                  <template v-slot:read-and-edit="{ editable }">
                    <audit-advanced-group
                      :expand="moneyExpand"
                      :expand-str="'moneyExpand'"
                      :group-label="'问题涉及金额列表'"
                      tablestyle="''"
                      @changedClick="changedClick"
                    >
                      <xm-child-table
                        v-model="model.iamExternalFindMoneyEntitys"
                        :read-only="!editable"
                        label=""
                        :class="$style.deptPlanChild"
                        :colspan="4"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                              attr: {},
                            },
                          ].concat(Array.from(fields.iamExternalFindMoneyEntitys.attr.dync))
                        "
                        :columns="moneycolumns"
                        :width="1000"
                        @change="changetablemoney"
                        @saved="changetablemoney"
                      >
                      </xm-child-table
                    ></audit-advanced-group>
                  </template> </sd-form-item
              ></td>
            </tr>
            <tr v-show="moneyExpand">
              <sd-form-item-td :label="null" name="reservestring1" :colspan="4">
                <template v-slot:read-and-edit="{ editable }">
                  <table style="width: 100%">
                    <tr
                      ><td
                        v-if="editable"
                        style="width: 60px; border: none"
                        class="ant-form-item-label ant-form-item-label"
                      ></td
                      ><td
                        style="width: 80px; border: none"
                        class="ant-form-item-label ant-form-item-label"
                      ></td>
                      <td
                        style="width: 50%; border: none"
                        class="ant-form-item-label ant-form-item-label"
                        ><label title="合计" class=""> 合计 </label></td
                      ><td style="border: none; border-left: 1px solid #e8e8e8"
                        ><span>{{ model.reservestring1 }}</span></td
                      ></tr
                    >
                  </table>
                </template>
              </sd-form-item-td>
            </tr>
          </table>

          <!-- 发现分类树 -->
          <a-modal
            :visible="findcatvisible"
            title="请选择"
            width="700px"
            :body-style="{
              height: '392px',
            }"
            :destroy-on-close="true"
            @ok="handlefindcatOk"
            @cancel="handlefindcatCancel"
          >
            <AuditFindCatTree :default-expand-all="true" @treeSelect="treeSelect" />
          </a-modal>

          <a-modal
            :visible="stepnamevisible"
            title="请选择"
            width="1200px"
            :body-style="{
              minHeight: '700px',
            }"
            :destroy-on-close="true"
            @ok="handlestepOk"
            @cancel="handlestepCancel"
            ><sd-data-table
              ref="stepTable"
              :class="$style.levelTable"
              :columns="stepmodalcolumns"
              data-url="api/xcoa-mobile/v1/audit-report-find/find-step"
              check-type="radio"
              show-selection
              :row-key="'ID'"
            />
          </a-modal>
          <a-modal
            :visible="findvisible"
            title="请选择"
            width="1200px"
            :body-style="{
              minHeight: '780px',
            }"
            :destroy-on-close="true"
            @ok="handlefindOk"
            @cancel="handlefindCancel"
          >
            <sd-data-table-ex
              ref="findTable"
              class="modalTable"
              check-type="radio"
              :filter-expressions="expressions"
              :columns="findcolumns"
              form-id="iamProblem"
              page-id="audit/auditsource/problem/iamProblem"
              :search-fields="['docTitle', 'problemNumber']"
              show-selection
            >
            </sd-data-table-ex>
          </a-modal>
        </template>
      </sd-detail-form>
    </audit-form-top-banner>
    <audit-matters-select-modal
      :visible="visible"
      :org-id="null"
      :show-selection="showSelectionlaw"
      @listSelected="listSelected"
    ></audit-matters-select-modal>
  </span>
</template>

<script>
import { Message, Modal } from 'ant-design-vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditFormTopBanner from '../../../components/audit-form-top-banner'
import auditAdvancedGroup from '../../../components/audit-advanced-group.vue'
import AuditFindCatTree from '../../../components/audit-find-cat-tree.vue'

import auditAdvancedGroupMixins from '../../../components/audit-advanced-group-mixins'
import auditMattersSelectModal from '../../matters/audit-matters-select-modal.vue'
import components from './_import-components/iam-audit-external-project-find-form-import'

const moneycolumns = [
  {
    title: '序号',
    dataIndex: 'sortNum',
    customRender: (text, record, index) => `${index + 1}`,
    width: '80px',
  },
  {
    title: '问题金额性质',
    dataIndex: 'assetType',
    sdHidden: true,
    width: '25%',
  },
  {
    title: '问题分类',
    dataIndex: 'problemClass',
  },
  {
    title: '合规性问题分类',
    dataIndex: 'complianceProblem',
  },
  {
    title: '问题金额（万元）',
    dataIndex: 'amount',
  },
]
const ruleclumns = [
  {
    title: '序号',
    dataIndex: 'sortNum',
    customRender: (text, record, index) => `${index + 1}`,
    width: '80px',
  },
  {
    title: '标题',
    dataIndex: 'ruleName',
  },
  {
    title: '发文字号',
    dataIndex: 'ruleNumber',
  },
  {
    title: '条文',
    dataIndex: 'ruleContent',
  },
]
const stepmodalcolumns = [
  // {
  //   title: '序号',
  //   dataIndex: 'sortNum',
  //   customRender: (text, record, index) => `${index + 1}`,
  //   width: '50px',
  // },
  {
    title: '步骤',
    dataIndex: 'STEP_NAME',
  },
  {
    title: '重要性',
    dataIndex: 'IMPORTANCE',
  },
  {
    title: '是否执行',
    dataIndex: 'IS_EXECITED',
  },
]
const findcolumns = [
  {
    title: '序号',
    dataIndex: 'sortNum',
    customRender: (text, record, index) => `${index + 1}`,
    width: '80px',
  },
  {
    title: '问题标题',
    dataIndex: 'docTitle',
  },
  {
    title: '问题编号',
    dataIndex: 'problemNumber',
  },
  {
    title: '问题描述',
    dataIndex: 'problemDesc',
  },
]
export default {
  name: 'IamAuditExternalProjectFindForm',
  metaInfo: {
    title: '审计发现',
  },
  components: {
    ...components,
    auditFormTopBanner,
    auditAdvancedGroup,
    AuditFindCatTree,
    auditMattersSelectModal,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      moneyExpand: true,
      basicExpand: true,
      ruleExpand: true,
      moneycolumns,
      ruleclumns,
      findcolumns,
      expressions: [],
      stepnamevisible: false,
      stepmodalcolumns,
      projectId: '',
      findcat: '',
      findcatvisible: false,
      visible: false,
      mode: null,
      findvisible: false,
      findType: '',
      problemCategoryFunction: '',
    }
  },
  mounted() {},
  created() {
    let projectId = ''
    if (this.$route.query.projectId) {
      projectId = this.$route.query.projectId
      if (projectId !== '' && projectId !== undefined) {
        this.projectId = projectId
      }
    }
    this.mode = this.$route.query.mode
    // this.changetablemoney()
  },
  methods: {
    showSelectionlaw(record) {
      this.selectlist = this.$refs.ruleData.value
      if (this.selectlist.length === 0) {
        return true
      } else if (
        this.selectlist.findIndex(
          (i) => i.ruleName + '-' + i.ruleNumber === record.docTitle + '-' + record.dispatchWord
        ) > -1
      ) {
        return false
      } else {
        return true
      }
    },
    initParam(model) {
      debugger
      const findcatstr = model.problemCategoryFunction
      if (findcatstr !== '' && findcatstr !== undefined) {
        const findcatobj = JSON.parse(findcatstr)
        this.problemCategoryFunction = findcatobj.text
      }
      return true
    },
    sdFormReady() {
      this.mode = this.$refs.docform.formData.mode
    },
    // 保存
    saveForm() {
      if (this.projectId !== '' && this.projectId !== undefined) {
        this.$refs.docform.setFieldValue('projectId', this.projectId)
      }
      // 处理部门
      var auditedUnits = this.$refs.docform.getFieldValue('auditedUnit')
      if (auditedUnits) {
        this.$refs.docform.setFieldValue(
          'auditedUnitIds',
          auditedUnits
            .map((item) => {
              return item.code
            })
            .toString()
        )
        this.$refs.docform.setFieldValue(
          'auditedUnitNames',
          auditedUnits
            .map((item) => {
              return item.name
            })
            .toString()
        )
      }

      let toSubmit = true // 默认可以提交
      let iamAuditMoneys = []
      if (this.$refs.docform.getFieldValue('iamExternalFindMoneyEntitys')) {
        iamAuditMoneys = this.$refs.docform.getFieldValue('iamExternalFindMoneyEntitys')
      }
      const newMoneysList = []
      iamAuditMoneys.forEach((item, index) => {
        if (
          item.problemClass === '01' &&
          (item.complianceProblem === '' ||
            item.complianceProblem === null ||
            item.complianceProblem === undefined)
        ) {
          toSubmit = false
          // newMoneysList.push(item)
        } else if (
          item.problemClass === '02' &&
          (item.complianceProblem === '' ||
            item.complianceProblem === 'null' ||
            item.complianceProblem === undefined)
        ) {
          item.complianceProblem = null
          newMoneysList.push(item)
        } else {
          newMoneysList.push(item)
        }
      })
      if (toSubmit) {
        this.$refs.docform.setFieldValue('iamExternalFindMoneyEntitys', newMoneysList)
        this.$refs.docform.saveBtnClick()
      } else {
        Modal.warning({
          title: '提示',
          content: '问题分类选择“合规性问题”时，合规性问题分类字段必填!',
        })
      }

      // this.$refs.docform.saveBtnClick()
    },
    saved() {
      Message.success('保存成功', 1).then((res) => {
        crossWindowWatcher.notifyChange(this.$route.fullPath, true)
        window.close()
      })
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, false)
      window.close()
    },
    treeSelect(select, info) {
      if (info.node) {
        this.findcat = info.node.dataRef
      } else {
        this.findcat = info
      }
      // this.$refs.docform.setFieldValue('paperId', this.findcat)
    },
    showfindcat() {
      this.findcatvisible = !this.findcatvisible
    },
    showstep(model) {
      this.stepnamevisible = !this.stepnamevisible
    },
    showfind(model) {
      this.findvisible = !this.findvisible
    },
    handlefindOk() {
      const selectInfo = this.$refs.findTable.getSelectedRows()
      if (selectInfo.length === 1) {
        this.$refs.docform.setFieldValue('findTitle', selectInfo[0].docTitle)
        // this.$refs.docform.setFieldValue('findCode', selectInfo[0].problemNumber)
        this.$refs.docform.setFieldValue('suggestion', selectInfo[0].problemDesc)
        this.showfind()
      } else {
        Modal.warning({
          title: '提示',
          content: '请选择一个发现问题!',
        })
        return false
      }
    },
    handlefindCancel() {
      this.showfind()
    },
    handlestepOk() {
      const selectInfo = this.$refs.stepTable.getSelectedRows()
      if (selectInfo.length) {
        this.$refs.docform.setFieldValue('stepName', selectInfo[0].STEP_NAME)
        this.showstep()
      }
    },
    handlestepCancel() {
      this.showstep()
    },
    changetablemoney(data) {
      let money = 0
      if (data && data.length > 0) {
        data.forEach((item, index) => {
          // item.sortNum = index + 1
          if (item.amount !== undefined) {
            money = money + parseFloat(item.amount)
          }
        })
        this.$refs.docform.setFieldValue('reservestring1', this.getTotal(data).toString())
      } else {
        this.$refs.docform.setFieldValue('reservestring1', '')
      }
    },
    handlefindcatOk() {
      if (this.findcat !== '') {
        if (this.findcat.isLeaf || !this.findcat.expandable) {
          this.$refs.docform.setFieldValue(
            'problemCategoryFunction',
            JSON.stringify({
              id: this.findcat.id,
              text: this.findcat.text,
            })
          )
          this.showfindcat()
          this.problemCategoryFunction = this.findcat.text
          this.findcat = ''
        } else {
          Modal.warning({
            title: '提示',
            content: '请选择末级分类!',
          })
          return false
        }
      } else {
        Modal.warning({
          title: '提示',
          content: '请选择末级分类!',
        })
        return false
      }
    },
    handlefindcatCancel() {
      this.showfindcat()
    },
    listSelected(keys, keyinfos) {
      let iamAuditLaws = []
      if (this.$refs.docform.getFieldValue('iamExternalFindRuleEntitys')) {
        iamAuditLaws = this.$refs.docform.getFieldValue('iamExternalFindRuleEntitys')
      }
      keyinfos.forEach((element) => {
        const mmc = {}
        mmc.ruleName = element.docTitle
        mmc.ruleNumber = element.dispatchWord ? element.dispatchWord : ''
        mmc.ruleContent = ''
        iamAuditLaws.push(mmc)
      })
      this.visible = false
      this.$refs.docform.setFieldValue('iamExternalFindRuleEntitys', iamAuditLaws)
    },
    // 选择法律制度
    lawsRelSelect() {
      // 选择事项分类
      this.visible = true
    },
    changetable(data) {
      data.forEach((item, index) => {
        item.sortNum = index + 1
      })
    },
    deletefind(ids) {},
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';
.first-tr {
  td {
    background: #fff !important;
    border: none !important;
  }
}
.btnselect {
  position: relative;
  left: 20px;
  float: right;
  .batchselect {
    top: 4px;
    z-index: 100;
    margin-right: 120px;
  }
  // position: relative;
  // float: right;
  // .batchselect {
  //   top: 4px;
  //   z-index: 100;
  //   margin-right: 190px;
  // }
}

.form {
  :global .iamAuditExternalProjectFindForm > td.ant-form-item-label > label {
    width: 220px;
    white-space: break-spaces !important;
  }
}
</style>
