<template>
  <audit-form-top-banner
    ref="banner"
    :handel-submit-form="alreadyflag ? submitForm : null"
    :handel-save-form="filingflag ? saveForm : null"
    :handel-rollback="stayflag ? handelRollback : null"
    @handelRollback="handelRollback"
    @handelSubmitForm="submitForm"
    @handelSaveForm="saveForm"
  >
    <sd-detail-form
      ref="docform"
      form-id="iamArchivesMaintain"
      page-id="audit/archives/iamArchivesMaintain"
      :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
      :class="$style.form"
      :read-only="readOnly"
      @close="close(true)"
      @saved="saved"
    >
      <template v-slot="{ model, fields }">
        <table>
          <tr>
            <td style="border:none;padding-left:5px">
              <audit-advanced-group
                :expand="templateExpand"
                :expand-str="'templateExpand'"
                :group-label="'基本信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="templateExpand">
          <!--自动生成 系统档案-->
          <tr v-if="model.archivesType === 'SYSTEM_FILE'">
            <!-- 项目名称 -->
            <td class="ant-form-item-label ant-form-item-label"
              ><label title="项目名称"> 项目名称 </label></td
            >
            <sd-form-item-td name="projectName" :label="null">
              <span>{{ model.projectName }}</span>
            </sd-form-item-td>
            <!-- 档案编号 -->
            <td class="ant-form-item-label ant-form-item-label"
              ><label title="档案编号"> 档案编号 </label></td
            >
            <sd-form-item-td name="archivesCode" :label="null">
              <span>{{ model.archivesCode }}</span>
            </sd-form-item-td>
          </tr>
          <tr v-if="model.archivesType === 'SYSTEM_FILE'">
            <!-- 档案类型 -->
            <td class="ant-form-item-label ant-form-item-label"
              ><label title="档案类型"> 档案类型 </label></td
            >
            <sd-form-item-td name="archivesType" :label="null">
              <span>系统档案</span>
            </sd-form-item-td>
            <!--  项目所属年度 -->
            <td class="ant-form-item-label ant-form-item-label"
              ><label title="项目所属年度"> 项目所属年度 </label></td
            >
            <sd-form-item-td name="planYear" :label="null">
              <span>{{ model.planYear }}</span>
            </sd-form-item-td>
          </tr>

          <!--自动生成 手动生成档案-->
          <tr v-if="model.archivesType !== 'SYSTEM_FILE'">
            <!-- 项目名称 -->
            <sd-form-item-td name="projectName" />
            <!-- 档案编号 -->
            <!-- <sd-form-item-td name="archivesCode" /> -->
            <sd-form-item-td name="archivesCode">
              <a-form-model-item
                :rules="[
                  {
                    validator: validator,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="archivesCode"
              >
                <a-input v-model="model.archivesCode"></a-input>
              </a-form-model-item>
            </sd-form-item-td>
          </tr>
          <tr v-if="model.archivesType !== 'SYSTEM_FILE'">
            <!-- 档案类型 -->
            <sd-form-item-td name="archivesType">
              <a-select v-model="model.archivesType">
                <a-select-option :value="'HISTORY_FILE'">
                  历史档案
                </a-select-option>
                <a-select-option :value="'OFFLINE_FILE'">
                  线下档案
                </a-select-option>
              </a-select>
            </sd-form-item-td>
            <!--  项目所属年度 -->
            <sd-form-item-td name="planYear">
              <a-date-picker
                v-model="model.planYear"
                mode="year"
                picker="YYYY"
                format="YYYY"
                :allow-clear="false"
                placeholder="选择年度"
                :input-read-only="true"
                :value="year"
                :open="endOpen"
                @panelChange="yearChange"
                @openChange="handleEndOpenChange"
              ></a-date-picker>
            </sd-form-item-td>
          </tr>

          <tr>
            <!-- 简要描述 -->
            <sd-form-item-td name="brieflyDesc" :colspan="3">
              <a-textarea v-model="model.brieflyDesc" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr v-if="model.archivesType === 'SYSTEM_FILE'">
            <td class="ant-form-item-label ant-form-item-label"
              ><label title="案卷状态"> 案卷状态 </label></td
            >
            <sd-form-item-td name="fileState" :label="null">
              <span>
                {{ getDictValue(fields.fileState.attr.selectListItem, model.fileState) }}
              </span>
            </sd-form-item-td>
          </tr>
          <tr v-else>
            <sd-form-item-td name="fileState" :colspan="3" />
          </tr>
          <tr>
            <!-- 最后修改时间 -->
            <sd-form-item-td name="lastModifiedTime" />
            <!-- 归档日期 -->
            <sd-form-item-td name="filingDate" />
          </tr>
          <tr>
            <!-- 编制人员 -->
            <sd-form-item-td name="creatorName" />
            <!-- 编制日期 -->
            <sd-form-item-td v-if="initparams(model)" name="creationTime" />
          </tr>
          <tr>
            <!-- 所属单位 -->
            <sd-form-item-td name="belongDeptMember" :colspan="3" />
            <!-- ID -->
            <sd-form-item-td :hidden="true" name="id" :colspan="3" />
          </tr>
        </table>

        <table>
          <tr>
            <td style="border:none;padding-left:5px">
              <audit-advanced-group
                :expand="expandA"
                :expand-str="'expandA'"
                :group-label="'案卷信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="expandA">
          <AuditArchivesTree
            ref="tree1"
            :status="fileState"
            :archives-type="archivesType"
            :fromflag="fromFlag"
            :userinfoname="userInfoName"
            :columns="childAJColumns"
            :actions="childAJActions"
            form-id="iamDossierData"
            page-id="audit/archives/iamDossierData"
            :treeparams="{
              configId: '22',
            }"
            :change="treechange"
            :record-id="recordId"
          >
          </AuditArchivesTree>
        </table>
      </template>
    </sd-detail-form>
  </audit-form-top-banner>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import { Modal, Message } from 'ant-design-vue'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
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 auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import AuditArchivesTree from './audit-archives-tree'
import components from './_import-components/audit-archives-form-import'

export default {
  name: 'AuditArchivesForm',
  metaInfo: {
    title: '档案管理',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    auditFormTopBanner,
    AuditArchivesTree,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      isSave: false, // 是否保存
      endOpen: false,
      year: null,
      alreadyflag: true,
      filingflag: false,
      stayflag: false,
      treeId: '',
      expandA: true,
      saveFlag: true,
      templateExpand: true,
      readOnly: false,
      flag: true,
      fileState: '',
      archivesType: '',
      fromFlag: '',
      userInfoName: '',
      recordId: '',
      childAJColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'id', sdHidden: true },

        {
          title: '文件名称',
          dataIndex: 'docTitle',
          scopedSlots: { customRender: 'islink' },
          width: '50%',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          defaultSortOrder: 'descend', // 没有点击任何排序列时，默认的排序列
          sdRender: TableColumnTypes.date,
        },
      ],
      customaction: {
        label: '新建',
        id: 'new',
        permission: 'create',
        type: TableActionTypes.primary,
        callback: () => {
          if (this.treeId != null && this.treeId !== undefined && this.treeId !== '') {
            // const archivesId = this.$route.query.record
            const archivesId = this.recordId
            const parentId = this.treeId
            const fromFlag = this.$route.query.fromFlag
            let fileState = this.fileState
            if (fileState === undefined) {
              fileState = this.$refs.docform.getFieldValue('fileState')
              this.fileState = fileState
            }
            const userInfo = getUserInfo()
            const url =
              '/audit-dossier-form?archivesId=' +
              archivesId +
              '&parentId=' +
              parentId +
              '&fileState=' +
              fileState +
              '&fromFlag=' +
              fromFlag +
              '&userInfoName=' +
              userInfo.name // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refresh()
              }
            })
          } else {
            Modal.confirm({
              title: '提示',
              content: '请先选择案卷信息分类。',
              okText: '确定',
              okType: 'danger',
            })
          }
        },
      },
      deletaction: {
        label: '删除',
        id: 'delete',
        type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理
      },
      flagcreat: true,
      childAJActions: [
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理
        },
      ],
    }
  },
  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() {
    // 监听关闭事件，关闭时如果没有保存操作且没有id，则直接删除所有子表
    window.addEventListener('beforeunload', (e) => {
      this.beforeunloadHandler(e)
    })
  },
  created() {
    if (this.$route.query.record) {
      this.recordId = this.$route.query.record
      this.fromFlag = this.$route.query.fromFlag
    } else {
      // 使用随机ID
      this.recordId = this.randomId
    }
  },
  methods: {
    // 获取字典值
    getDictValue(list, val) {
      return list.find((item) => {
        return item.value.trim() === (val + '').trim()
      })?.label
    },
    // 关闭窗口监听
    beforeunloadHandler(e) {
      if (!this.isSave && !this.$refs.flow.getFieldValue('id')) {
        // 此处需要调用接口删除所有档案关联的临时ID数据，否则会有脏数据
        axios({
          url: 'api/xcoa-mobile/v1/iamarchivesmaintain/deletedArchives?id=' + this.recordId,
          method: 'post',
        })
      }
    },
    validator(rule, value, callback) {
      value = encodeURIComponent(value)
      const id = this.$route.query.record || ''
      debounce(() => {
        axios
          .get(
            `api/xcoa-mobile/v1/iamarchivesmaintain/findArchivesCode?archivesCode=${value}&id=` + id
          )
          .then((res) => {
            if (res?.data === true) {
              callback()
            } else {
              callback('已存在，不允许重复')
            }
          })
      }, 500)()
    },
    yearChange(value) {
      this.year = value
      this.$refs.docform.setFieldValue('planYear', value.format('YYYY'))
      this.$refs.docform.validateField('planYear').then((res) => {
        console.log(res)
      })
      if (document.getElementsByClassName('ant-calendar-picker-container').length > 0) {
        document.getElementsByClassName('ant-calendar-picker-container')[0].style.display = 'none'
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open
    },
    initparams(model) {
      if (this.flagcreat) {
        this.flagcreat = false
        this.fileState = model.fileState
        const fromFlag = this.$route.query.fromFlag
        const userInfo = getUserInfo()
        if (fromFlag === 'projectList') {
          this.stayflag = false
          this.filingflag = true
        } else if (model.creatorName === userInfo.name) {
          if (this.fileState === 'FILING' || model.fileState === undefined) {
            this.filingflag = true
          } else if (this.fileState === 'ALREADY_FILE') {
            this.alreadyflag = false
            this.stayflag = true
            this.childAJActions = []
            this.readOnly = true
          } else {
            this.alreadyflag = true
            this.stayflag = true
            this.childAJActions = []
            this.readOnly = true
          }
        } else if (this.flag) {
          if (model.fileState !== undefined) {
            this.flag = false
            axios({
              url: 'api/xcoa-mobile/v1/iamarchivesmaintain/findHasPermission',
              method: 'post',
            }).then((res) => {
              if (res.data === true) {
                if (this.fileState === 'STAY_FILE') {
                  this.stayflag = true
                  this.readOnly = true
                  this.childAJActions = []
                }
                if (this.fileState === 'FILING') {
                  this.filingflag = true
                }
                if (this.fileState === 'ALREADY_FILE') {
                  this.alreadyflag = false
                  this.stayflag = true
                  this.childAJActions = []
                  this.readOnly = true
                }
              } else {
                this.alreadyflag = false
                this.readOnly = true
                this.childAJActions = []
              }
            })
          }
        }
        this.year = model.planYear
      }
      this.archivesType = model.archivesType
      return true
    },
    refresh() {
      return this.$refs.tree1.$refs.dataTable.refresh(true)
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    // 提交
    submitForm() {
      this.$refs.docform.validateFields().then(() => {
        this.$refs.docform.setFieldValue('randomId', this.recordId)
        const fileState = this.$refs.docform.getFieldValue('fileState')
        const archivesType = this.$refs.docform.getFieldValue('archivesType')

        // 自创档案 立卷————>已归档
        if (archivesType !== 'SYSTEM_FILE') {
          this.$refs.docform.setFieldValue('fileState', 'ALREADY_FILE')
        } else {
          // 自创档案 立卷————>待归档————>已归档
          // 立卷变待归档
          if (fileState === 'FILING') {
            this.$refs.docform.setFieldValue('fileState', 'STAY_FILE')
          }
          // 待归档变已归档
          if (fileState === 'STAY_FILE') {
            this.$refs.docform.setFieldValue('fileState', 'ALREADY_FILE')
          }
        }

        this.$refs.docform.save().then((res) => {
          const beanId = res.data.pageFormData.beanId
          if (window.location.href.indexOf('record') < 0) {
            this.$router.replace(`?record=` + beanId)
          }
        })

        Message.success('提交成功').then((res) => {
          this.isSave = true
          this.$refs.docform.saveBtnClick()
        })
      })
    },
    // 保存
    saveForm() {
      this.$refs.docform.validateFields().then(() => {
        this.$refs.docform.setFieldValue('randomId', this.recordId)
        this.$refs.docform.save().then((res) => {
          const beanId = res.data.pageFormData.beanId
          if (window.location.href.indexOf('record') < 0) {
            this.$router.replace(`?record=` + beanId)
          }
          this.isSave = true
          Message.success('保存成功')
        })
      })
    },
    saved() {
      this.close(true)
    },
    handelRollback() {
      this.$refs.docform.validateFields().then(() => {
        const fileState = this.$refs.docform.getFieldValue('fileState')
        // 已归档变待归档
        if (fileState === 'ALREADY_FILE') {
          this.$refs.docform.setFieldValue('fileState', 'STAY_FILE')
        }
        // 待归档变立卷
        if (fileState === 'STAY_FILE') {
          this.$refs.docform.setFieldValue('fileState', 'FILING')
        }
      })
      this.$refs.docform.saveBtnClick()
    },
    treechange(unableselect, id) {
      const userInfo = getUserInfo()
      const creatorName = this.$refs.docform.getFieldValue('creatorName')
      const fileState = this.$refs.docform.getFieldValue('fileState')
      this.treeId = id
      this.unableselect = unableselect
      this.childAJActions = []
      this.childAJActions.push(this.deletaction)
      const fromFlag = this.$route.query.fromFlag
      // const archivesId = this.$route.query.record
      // 用随机ID
      const archivesId = this.recordId
      const archivesType = this.$refs.docform.getFieldValue('archivesType')
      if (this.unableselect !== true && fromFlag === 'projectList') {
        this.childAJActions.push(this.customaction)
      } else if (this.unableselect !== true && archivesId === undefined) {
        Modal.confirm({
          title: '提示',
          content: '请先保存案卷管理基本信息',
          okText: '确定',
          okType: 'danger',
        })
      } else if (archivesType === 'SYSTEM_FILE') {
        if (creatorName === userInfo.name && (fileState !== 'FILING' || unableselect === true)) {
          this.childAJActions = []
        } else {
          this.childAJActions.push(this.customaction)
        }
      } else {
        axios({
          url: 'api/xcoa-mobile/v1/iamarchivesmaintain/findHasPermission',
          method: 'post',
        }).then((res) => {
          if (res.data !== true) {
            this.childAJActions = []
          } else if (fileState !== 'FILING' || unableselect === true) {
            if (fileState === 'STAY_FILE' || fileState === 'ALREADY_FILE') {
              this.alreadyflag = false
            }
            this.childAJActions = []
          } else {
            this.childAJActions.push(this.customaction)
          }
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';
</style>
