<template>
  <audit-form-top-banner
    :handel-save-form="saveForm"
    :handel-publish="publishflag ? handelPublish : null"
    :form-data="mode"
    @handelSaveForm="saveForm"
    @handelPublish="handelPublish"
  >
    <sd-detail-form
      ref="docform"
      page-id="audit/externalProject/iamExternalProject"
      :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
      :class="$style.form"
      @close="close(true)"
      @saved="saved"
      @sdFormReady="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 v-show="basicExpand">
          <tr v-show="false">
            <!-- id -->
            <sd-form-item-td name="id" />
            <sd-form-item-td name="randomId" :input-props="{ defaultValue: randomId }" />
          </tr>
          <tr>
            <!-- 项目名称 -->
            <sd-form-item-td name="projectTitle" />
            <!-- 项目编号 -->
            <sd-form-item-td name="projectCode">
              <!-- <a-input v-model="model.projectCode" :read-only="true"></a-input> -->
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 外部检查机构 -->
            <sd-form-item-td name="inspectionOrg" />
            <!-- 被检查机构 -->
            <sd-form-item-td name="auditedUnitNames" />
          </tr>
          <tr v-show="false">
            <sd-form-item-td :hidden="true" name="auditedUnitIds" />
          </tr>
          <tr>
            <!-- 外部项目联系人 -->
            <sd-form-item-td name="linkMan" />
            <!-- 被检查类型 -->
            <sd-form-item-td name="inspectionType" />
          </tr>

          <tr>
            <!-- 外部检查联系方式 -->
            <sd-form-item-td name="linkManNum" />
          </tr>

          <tr>
            <!-- 项目说明 -->
            <sd-form-item-td name="description" :colspan="3">
              <a-textarea v-model="model.description" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 检查开始日期 -->
            <sd-form-item-td name="inspectionStartTime" />
            <!-- 检查结束日期 -->
            <sd-form-item-td name="inspectionEndTime" />
          </tr>
          <tr>
            <!-- 检查区间开始日期 -->
            <sd-form-item-td name="sectionStartTime" />
            <!-- 检查区间结束日期 -->
            <sd-form-item-td name="sectionEndTime" />
          </tr>
          <tr>
            <!-- 创建人姓名 -->
            <sd-form-item-td name="creatorName" />
            <!-- 创建时间 -->
            <sd-form-item-td name="creationTime" />
          </tr>
          <tr>
            <!-- 附件 -->
            <sd-form-item-td name="attachment" :colspan="3" />
          </tr>
          <tr v-show="false">
            <sd-form-item-td v-if="initParam(model)" :hidden="true" name="releaseType" />
          </tr> </table

        ><table>
          <tr
            ><td :colspan="4">
              <sd-form-item name="iamExternalFindEntitys" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="findExpand"
                    :expand-str="'findExpand'"
                    :group-label="'审计发现'"
                    tablestyle="''"
                    @changedClick="changedClick"
                    ><template>
                      <template>
                        <div :class="$style.wrapper">
                          <div v-show="findExpand && editable" :class="$style.btnselect">
                            <a-button type="link" :class="$style.batchselect" @click="findImport">
                              <a-icon type="check-circle" :theme="'filled'" />批量导入
                            </a-button>
                          </div>
                        </div>
                      </template>
                      <div :class="[$style.btns]">
                        <audit-advanced-import
                          ref="sjzlImport"
                          :config-id="'151'"
                          :table-id="'findData'"
                          :relevant-column="relevant"
                          :v-if="false"
                          @importfromfileAfter="importfromfileAfter"
                        >
                        </audit-advanced-import>
                      </div>
                      <xm-paper-child-table
                        v-show="findExpand"
                        :key="findDataKey"
                        ref="findData"
                        v-model="iamExternalFindEntitys"
                        :mode="mode"
                        :class="$style.deptPlanChild"
                        :label="null"
                        :colspan="8"
                        :columns="findcolumns"
                        name="iamExternalFindEntitys"
                        :project-id="record"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                              attr: {},
                            },
                          ].concat(Array.from(fields.iamExternalFindEntitys.attr.dync).slice(0, 6))
                        "
                        :creatnewfind="creatnewfind"
                        :deletefind="deletefind"
                        :findtable="true"
                        :captionvisiable="true"
                        :read-only="!editable"
                        @change="changetable"
                      >
                      </xm-paper-child-table>
                    </template>
                  </audit-advanced-group>
                </template> </sd-form-item
            ></td>
          </tr> </table

        ><table>
          <tr
            ><td :colspan="4">
              <sd-form-item name="iamExternalFileEntitys" :label="null">
                <!-- input-form 表示这部分是子表组件的form插槽 -->
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="expandY"
                    :expand-str="'expandY'"
                    :group-label="'项目相关文件'"
                    @changedClick="changedClick"
                    ><template>
                      <xm-child-table
                        v-model="model.iamExternalFileEntitys"
                        :read-only="!editable"
                        label=""
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                              attr: {},
                            },
                          ].concat(Array.from(fields.iamExternalFileEntitys.attr.dync))
                        "
                        :columns="childLawsColumns"
                        :width="1000"
                      >
                      </xm-child-table
                    ></template>
                  </audit-advanced-group>
                </template> </sd-form-item
            ></td>
          </tr>
        </table>
      </template>
    </sd-detail-form>
  </audit-form-top-banner>
</template>

<script>
import { Modal, Message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditFormTopBanner from '../../components/audit-form-top-banner'
import auditAdvancedImport from '../../components/audit-advanced-import.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import components from './_import-components/iam-audit-external-project-form-import'
import xmPaperChildTable from './table/xm-paper-child-table.vue'
import AuditExternalProjectService from './iam-audit-external-project-service.js'
export default {
  name: 'IamAuditExternalProjectForm',
  metaInfo: {
    title: '外部项目',
  },
  components: {
    ...components,
    auditFormTopBanner,
    auditAdvancedGroup,
    xmPaperChildTable,
    auditAdvancedImport,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      findDataKey: 0,
      isSave: false, // 是否为保存操作
      relevant: this.$route.query.record * 1,
      publishflag: false,
      record: '',
      basicExpand: true,
      message: '保存成功',
      expandY: true,
      mode: null,
      findExpand: true,
      labelArray: [],
      fileFileds: [],
      findcolumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '5.8%',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '问题名称（定性描述）',
          dataIndex: 'findTitle',
          scopedSlots: { customRender: 'islink' },
        },
        { title: '审计问题编号', dataIndex: 'findCode' },
        {
          title: '问题类别',
          dataIndex: 'problemType',
          scopedSlots: { customRender: 'problemType' },
          sdHidden: true,
        },
        {
          title: '问题分类',
          dataIndex: 'problemCategoryFunction',
          customRender: (text, record, index) => JSON.parse(text).text,
        },
        // { title: '被检查机构', dataIndex: 'auditedUnitNames' },
        { title: '被审计单位', dataIndex: 'auditedUnitNames' },
        { title: '发送整改状态', dataIndex: 'sendStatus' },
      ],
      childLawsColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '5%',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'fileType',
          title: '文件类型',
          width: '15%',
        },
        {
          dataIndex: 'fileTitle',
          width: '15%',
          title: '文件名称',
        },
        {
          dataIndex: 'fileDesc',
          width: '15%',
          title: '文件说明',
        },
      ],
      iamExternalFindEntitys: [],
    }
  },
  computed: {
    // 计算随机key
    randomId() {
      let randomNum = Math.random()
      while (randomNum === 0) {
        randomNum = Math.random()
      }
      const time = new Date().getTime()
      return time + Math.ceil(randomNum * 1000000000)
    },
  },
  mounted() {
    window.addEventListener('beforeunload', (e) => {
      this.beforeunloadHandler(e)
    })
    this.record = this.$route.query.record
    if (this.record) {
      this.getExternalrFind(this.record)
    }
  },
  methods: {
    beforeunloadHandler(e) {
      if (!this.isSave && !this.$refs.docform.getFieldValue('id')) {
        const strid = this.iamExternalFindEntitys.map((item) => {
          return item.id
        })
        if (strid.length > 0) {
          axios({
            url: 'api/xcoa-mobile/v1/iamexternalfind/deletedFind?ids=' + strid.join(','),
            method: 'post',
          })
        }
      }
    },
    findImport() {
      if (!this.relevant) {
        this.relevant = this.randomId
      }
      this.$refs.sjzlImport.showImportPanel()
    },
    importfromfileAfter() {
      let record
      if (this.record === undefined || this.record === '') {
        record = this.randomId
      } else {
        record = this.record
      }
      const params = { projectId: record }
      AuditExternalProjectService.getAuditFindData(params).then((res) => {
        this.$refs.docform.setFieldValue('iamExternalFindEntitys', res.data)
        this.iamExternalFindEntitys = res.data
      })
    },
    sdFormReady() {
      this.mode = this.$refs.docform.formData.mode
      // this.$refs.docform.setFieldValue('randomId', this.randomId)
    },
    initParam(model) {
      if (model.releaseType !== 1) {
        this.publishflag = true
      }
      return true
    },
    handelPublish() {
      this.$refs.docform.setFieldValue('releaseType', 1)
      this.message = '发布成功！'
      this.saveForm()
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    // 保存
    saveForm() {
      this.isSave = true
      const auditedUnitNames = this.$refs.docform.getFieldValue('auditedUnitNames')
      // 处理部门
      if (auditedUnitNames) {
        this.$refs.docform.setFieldValue(
          'auditedUnitIds',
          auditedUnitNames
            .map((item) => {
              return item.code
            })
            .toString()
        )
      }
      this.$refs.docform.saveBtnClick()
    },
    saved(data) {
      // 拼接record
      if (!this.$route.fullPath.includes('record')) {
        this.$router.replace(`/audit-externalProject-form?record=${data.pageFormData.beanId}`)
        // 刷新审计发现子表
        this.getExternalrFind(data.pageFormData.beanId)
        this.record = data.pageFormData.beanId
      }
      Message.success({ content: this.message }).then(() => {
        crossWindowWatcher.notifyChange(this.$route.fullPath, true)
        // 发布就关闭
        if (this.message === '发布成功！') {
          this.close(true)
        }
      })
    },
    getExternalrFind(projectId) {
      // 获取发现列表
      const params = { projectId: projectId }
      AuditExternalProjectService.getAuditFindData(params).then((res) => {
        res.data.forEach((item, index) => {
          item.sortNum = index + 1
        })
        this.iamExternalFindEntitys = res.data
      })
    },
    changeNum(data) {
      data.forEach((item, index) => {
        item.sortNum = index + 1
      })
    },
    creatnewfind() {
      let record
      if (this.record === undefined || this.record === '') {
        record = this.randomId
      } else {
        record = this.record
      }
      const url = '/audit-externalProject-find-form?projectId=' + record // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          setTimeout(this.getExternalrFind(record), 3000)
        }
      })
    },
    deletefind(ids) {
      const strid = ids.join(',')
      axios({
        url: 'api/xcoa-mobile/v1/iamexternalfind/deletedFind?ids=' + strid,
        method: 'post',
      })
    },
    changetable(data) {
      data.forEach((item, index) => {
        item.sortNum = index + 1
      })
    },
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';
.ant-card-body {
  padding: 12px;
}
.btnselect {
  position: relative;
  float: right;
  .batchselect {
    top: 4px;
    z-index: 100;
    margin-right: 190px;
  }
}
</style>
