<template>
  <span>
    <audit-form-top-banner
      :handel-save-form="saveForm"
      :handel-publish="handelPublish"
      :form-data="mode"
      :model="searchForm"
      :hiden-or-show="hidenOR0Show"
      @handelSaveForm="saveForm"
      @handelPublish="handelPublish"
    >
      <sd-detail-form
        ref="docform"
        page-id="audit/spicannualreportpublish/spicAnnualReportPublish"
        :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
        :class="$style.form"
        :read-only="readOnly"
        @close="close(true)"
        @saved="saved"
        @sdFormReady="sdFormReady"
      >
        <template v-slot="{ model, fields }">
          <div v-show="loading" :class="$style.loadingDiv">
            <a-spin :spinning="true" tip="创建数据中..." />
          </div>
          <!-- <table :class="$style.table">
            <colgroup>
              <col :class="$style.label" />
              <col :class="$style.input" />
              <col :class="$style.label" />
              <col :class="$style.input" />
            </colgroup> -->
          <table>
            <tr>
              <sd-form-item-td name="fileTitle" :colspan="10" />
              <sd-form-item-td name="reportYear" :colspan="10">
                <a-date-picker
                  v-model="model.reportYear"
                  mode="year"
                  picker="YYYY"
                  format="YYYY"
                  :allow-clear="false"
                  placeholder="选择年度"
                  :input-read-only="true"
                  :open="endOpen"
                  :value="year"
                  @panelChange="yearChange"
                  @openChange="handleEndOpenChange"
                ></a-date-picker>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="auditedUnit" :colspan="10" />
              <sd-form-item-td name="lastTime" :colspan="10" />
            </tr>
            <tr>
              <sd-form-item-td name="description" :colspan="21">
                <a-textarea v-model="model.description" :rows="3" />
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 文档附件 -->
              <sd-form-item-td name="attachment" :colspan="21" />
            </tr>
            <tr>
              <sd-form-item-td name="viewPeoples" :colspan="21" />
            </tr>
            <tr>
              <sd-form-item-td name="creatorName" :colspan="10" />
              <sd-form-item-td name="creationTime" :colspan="10" />
            </tr>
            <tr>
              <sd-form-item-td name="uuid" :colspan="10" hidden="true" />
            </tr>
          </table>

          <table>
            <tr
              ><td :colspan="4">
                <sd-form-item
                  name="spicAnnualReportPublishItemEntities"
                  :label="null"
                  :input-td-attrs="{ class: 'annualReportPublishItemEntities' }"
                >
                  <template v-slot:read-and-edit="{ editable }">
                    <audit-advanced-group
                      :expand="moneyExpand"
                      :expand-str="'moneyExpand'"
                      :group-label="'年度报告'"
                      @changedClick="changedClick"
                    >
                      <template>
                        <div v-show="moneyExpand && editable" :class="$style.btnmubandiv">
                          <a-button type="link" :class="$style.btnmuban" @click="showImportTable"
                            ><a-icon type="check-circle" :theme="'filled'" />
                            用模板创建
                          </a-button>
                        </div>
                        <!-- :read-only="!editable" -->
                        <sd-child-table
                          ref="childTable"
                          v-model="model.spicAnnualReportPublishItemEntities"
                          :class="$style.deptPlanChild"
                          label=""
                          :read-only="!childEdit"
                          :sequence-column="true"
                          :fields="Array.from(fields.spicAnnualReportPublishItemEntities.attr.dync)"
                          :columns="childColumns"
                          @change="changeCTable"
                        >
                          <!-- input-form 表示这部分是子表组件的form插槽 -->
                          <template v-slot:form="{ model, fields }">
                            <table :class="$style.xmTable">
                              <tr>
                                <sd-form-item-td name="dataName" :colspan="3" />
                              </tr>
                              <tr>
                                <sd-form-item-td name="dataDesc" :colspan="3">
                                  <a-textarea v-model="model.dataDesc" :rows="3" />
                                </sd-form-item-td>
                              </tr>
                              <tr>
                                <!-- 资料类型 -->
                                <sd-form-item-td
                                  name="dataType"
                                  component="a-select"
                                  :colspan="3"
                                />
                              </tr>
                              <tr>
                                <sd-form-item-td name="attachment" :colspan="3" />
                              </tr>
                            </table>
                          </template>
                        </sd-child-table>
                      </template>
                    </audit-advanced-group>
                  </template>
                </sd-form-item>
              </td>
            </tr>
          </table>
        </template>
      </sd-detail-form>
    </audit-form-top-banner>
    <!-- 选择导入模板 -->
    <a-modal
      :visible="visible"
      title="选择模板"
      width="50%"
      :destroy-on-close="true"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <sd-data-table-ex
        ref="importTable"
        check-type="radio"
        :filter-expressions="expressions"
        :columns="columns2"
        form-id="iamTemplate"
        page-id="audit/template/iamTemplate"
        :search-fields="['templateName', 'templateType', 'isDefault']"
        show-selection
      >
      </sd-data-table-ex>
    </a-modal>
  </span>
</template>

<script>
import { Message, Modal } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import TableColumnTypes from '@/common/services/table-column-types'
import xmSpicAnnualReportService from './xm-spic-annual-report-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner'
import components from './_import-components/xm-annual-report-puiblish-form-import'

export default {
  name: 'XmAnnualReportPuiblishForm',
  metaInfo: {
    title: '年报资料下发',
  },
  components: { ...components, auditFormTopBanner, auditAdvancedGroup },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      columns2: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '70px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '模板名称',
          dataIndex: 'templateName',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '模板类型',
          dataIndex: 'templateType',
        },
        {
          title: '编制日期',
          dataIndex: 'authTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
          defaultSortOrder: 'desc',
        },
        {
          title: '附件',
          dataIndex: 'attachment',
          sdHidden: true,
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'templateType',
          op: 'like',
          stringValue: '%4%',
        },
      ],
      childColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '资料名称',
          dataIndex: 'dataName',
        },
        {
          title: '资料描述',
          dataIndex: 'dataDesc',
        },
        {
          title: '资料类型',
          dataIndex: 'dataType',
        },
        // {
        //   title: '附件',
        //   dataIndex: 'attachment',
        // },
      ],
      loading: false,
      projectId: null,
      visible: false,
      year: null,
      endOpen: false,
      moneyExpand: true,
      mode: null,
      hidenOR0Show: true,
      readOnly: false,
      childEdit: true,
      publish: 0, // 为1 时是发布
      hasOperatePermissions: true,
      showYearPicker: false,
      searchForm: {},
    }
  },
  methods: {
    // 页面加载完成后
    sdFormReady() {
      debugger
      const ini = setInterval(() => {
        if (
          this.$refs.docform &&
          (this.$refs.docform.$refs.form || this.$refs.docform.$refs.sdForm)
        ) {
          clearInterval(ini)
          this.mode = this.$refs.docform.formData.mode
          if (this.$refs.docform.formData.pageFormData.beanId) {
            const status = this.$refs.docform.getFieldValue('status')
            if (status === '已发布') {
              this.hidenOR0Show = false
              this.readOnly = true
              this.moneyExpand = false
              this.childEdit = false
              this.mode = 'VIEW'
            } else {
              const creatorAccount = this.$refs.docform.getFieldValue('creatorAccount')
              if (creatorAccount !== getUserInfo().account) {
                this.hidenOR0Show = false
                this.readOnly = true
                this.childEdit = false
                this.moneyExpand = false
                this.mode = 'VIEW'
              }
            }
          }
        }
      }, 100)
      // if (!this.hasOperatePermissions) {
      //   this.$refs.docform.formData.mode = 'VIEW'
      // }
      // this.mode = this.$refs.docform.formData.mode
      // const docStatus = this.$refs.docform.getFieldValue('status')
      // if (docStatus === '已发布') {
      //   this.hidenOR0Show = false
      // }
      axios({
        url: 'api/xcoa-mobile/v1/spicannualreportpublish/createSpicAnnualUuid',
        method: 'post',
      }).then((res) => {
        const uuid = res.data
        this.$refs.docform.setFieldValue('uuid', uuid)
      })
    },
    showImportTable() {
      this.visible = !this.visible
    },
    yearChange(value) {
      this.year = value
      this.$refs.docform.setFieldValue('reportYear', value.format('YYYY'))
      this.$refs.docform.validateField('reportYear').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
    },
    // 保存
    saveForm() {
      this.$refs.docform.saveBtnClick()
      this.$refs.docform.setFieldValue('status', '起草中')
    },
    handelPublish() {
      this.$refs.docform.validateFields().then(() => {
        Modal.confirm({
          title: '提示',
          content: '请确认是否发布当前数据',
          onOk: () => {
            // 发布，保存
            this.$refs.docform.setFieldValue('status', '已发布')
            this.publish = 1
            this.$refs.docform.save().then((res) => {
              const id = this.$refs.docform.getFieldValue('id')
              const uuid = this.$refs.docform.getFieldValue('uuid')
              axios({
                url: 'api/xcoa-mobile/v1/spicannualreportpublish/createSpicAnnualReportFlow',
                method: 'post',
                data: { uuid: uuid },
              })
                .then((res) => {
                  if (res.data.isRequestSuccess === 'false') {
                    Message.error('年度资料下发失败，请联系系统管理员')
                  } else {
                    Message.success('发布成功', 1).then((res) => {
                      this.close(true)
                    })
                  }
                })
                .catch(() => {
                  Message.error('服务异常')
                })
            })
          },
          onCancel: () => {},
        })
      })
    },

    saved() {
      if (this.publish === 1) {
        Message.success('发布成功', 1).then((res) => {
          this.close(true)
        })
      } else {
        Message.success('保存成功', 1).then((res) => {
          this.close(true)
        })
      }
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    // 弹出窗确认
    handleOk() {
      this.loading = true
      this.showImportTable()
      // 获取别选择的行信息
      const selectInfo = this.$refs.importTable.getSelectedRows()
      xmSpicAnnualReportService
        .importAnnualPeportPublishInfo(selectInfo[0].attachment)
        .then((res) => {
          Message.success('模板创建成功')
          const data = this.$refs.docform.getFieldValue('spicAnnualReportPublishItemEntities') || []
          const tableData = data.concat(res.data)
          tableData.forEach((item, index) => {
            if (!item.id) {
              item.id = 'fakeId' + index + 1
            }
          })
          this.$refs.docform.setFieldValue('spicAnnualReportPublishItemEntities', tableData)
          this.loading = false
        })
    },
    // 弹出窗取消
    handleCancel() {
      this.showImportTable()
    },
    changeCTable() {
      this.key++
    },
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';
.xm-table {
  :global(td.ant-form-item-label) {
    width: 15%;
  }
}
.btnmubandiv {
  position: relative;
  .btnmuban {
    position: absolute;
    top: 0;
    right: 190px;
    z-index: 100;
  }
}

.btnselect {
  position: relative;
  float: right;
  .batchselect {
    top: 4px;
    z-index: 100;
    margin-right: 200px;
  }
}
.form {
  :global .iamauditfindform > td.ant-form-item-label > label {
    white-space: break-spaces !important;
  }
}
.loading-div {
  position: absolute;
  z-index: 101;
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: rgb(255 255 255 / 70%);
}
</style>
