<template>
  <sd-webflow ref="flow" :removed-tabs="['sdRelatedDoc']" :validate-form="validateForm">
    <template v-slot:form="{ model, fields }">
      <table
        ><tr v-show="false">
          <!-- 1.标题 -->
          <sd-form-item-td name="title" />
          <!-- 2.报送单位Name -->
          <sd-form-item-td name="submitUnitCode" />
          <sd-form-item-td name="submitUserCode" />
        </tr>
        <tr>
          <sd-form-item-td name="submitUnit"> </sd-form-item-td>
          <sd-form-item-td name="submitUser"> </sd-form-item-td>
        </tr>

        <tr>
          <sd-form-item-td name="submitMonth" :input-props="{ disabled: true }" />
          <sd-form-item-td name="submitDate" />
        </tr>
        <tr v-show="false">
          <sd-form-item-td name="submitUserName" />
          <sd-form-item-td name="submitUnitName" />
        </tr>

        <tr>
          <!-- 8.创建人 -->
          <sd-form-item-td name="creatorName" />
          <!-- 9.创建日期 -->
          <sd-form-item-td name="creationTime" />
        </tr>
        <tr v-show="false">
          <!-- id -->
          <sd-form-item-td name="id" />
          <sd-form-item-td name="randomId" :input-props="{ defaultValue: randomId }" />
        </tr>
      </table>

      <table>
        <tr :class="$style.lastTr">
          <td :colspan="8">
            <sd-form-item-td :label="null" name="spicEngineConstruceProjectList">
              <template v-slot:read-and-edit="{ editable }">
                <template>
                  <div :class="$style.wrapper">
                    <div v-show="projectExpand && editable" :class="$style.btnselect">
                      <a-button type="link" :class="$style.batchselect" @click="getProject"
                        ><a-icon type="check-circle" :theme="'filled'" />生成数据
                      </a-button>
                      <a-button type="link" :class="$style.batchselect" @click="remove"
                        ><a-icon type="check-circle" :theme="'filled'" />删除
                      </a-button>
                    </div>
                  </div>
                </template>
                <audit-advanced-group
                  :expand="projectExpand"
                  :expand-str="'projectExpand'"
                  :group-label="'工程项目列表'"
                  ><template>
                    <xm-paper-child-table
                      ref="tabaData"
                      v-model="model.spicEngineConstruceProjectList"
                      :disable-ad="true"
                      :class="$style.deptPlanChild"
                      name="spicEngineConstruceProjectList"
                      label="信息填报"
                      :fields="
                        [
                          {
                            caption: '序号',
                            name: 'sortNum',
                            dataType: 'number',
                          },
                        ].concat(Array.from(fields.spicEngineConstruceProjectList.attr.dync))
                      "
                      :columns="childColumns"
                      :captionvisiable="false"
                      :flagpage="true"
                    >
                      <a
                        slot="projectName"
                        slot-scope="text, record"
                        @click="linkProject(text.record, editable)"
                        >{{ text.text }}</a
                      >
                    </xm-paper-child-table>
                  </template>
                </audit-advanced-group>
              </template>
            </sd-form-item-td>
          </td>
        </tr>
      </table>
    </template>
  </sd-webflow>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import xmPaperChildTable from '@product/iam/audit/work/operate/paper/table/xm-paper-child-table.vue'
import components from './_import-components/spic-engine-construce-base-form-import'
import axios from '@/common/services/axios-instance'
import { Message, Modal } from 'ant-design-vue'
import errorUtil from '@/common/services/error-util'

import { data } from 'vue-echarts'

export default {
  name: 'SpicEngineConstruceBaseForm',
  metaInfo: {
    title: '信息填报',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    xmPaperChildTable,
  },

  data() {
    return {
      auditUnit: [],
      selectedRowKeys: [],
      projectExpand: true,
      randomId: '',
      childColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'projectName',
          sorter: true,
          width: '15%',
        },
        { dataIndex: 'auditedUnitName', sorter: true, defaultSortOrder: 'ascend', width: '15%' },
        {
          dataIndex: 'auditType',
          sorter: false,
          customRender: (text, record, index) =>
            JSON.parse(text) === null ? '' : JSON.parse(text)[0].name,
          width: '15%',
        },
        { dataIndex: 'auditDecisionDate', sorter: true, width: '120px' },
        {
          dataIndex: 'submittedMonth',
          sorter: true,
          customRender: (text, record, index) =>
            JSON.parse(text) === null ? '' : JSON.parse(text)[0].name,
          width: '120px',
        },
        { dataIndex: 'submitUnitName', sorter: true, width: '120px' },
        {
          dataIndex: 'submittedQuarter',
          sorter: true,
          customRender: (text, record, index) =>
            JSON.parse(text) === null ? '' : JSON.parse(text)[0].name,
          width: '120px',
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'mainId', sdHidden: true },
        { dataIndex: 'investDecisionDate', sdHidden: true },
        { dataIndex: 'cumulativeInvestment', sdHidden: true },
        { dataIndex: 'commencementDate', sdHidden: true },
        { dataIndex: 'planedProductionDate', sdHidden: true },
        { dataIndex: 'projectCode', sdHidden: true },
      ],
    }
  },

  mounted() {
    this.initData()
    this.getRandomId()
  },
  methods: {
    getRandomId() {
      let randomNum = Math.random()
      while (randomNum === 0) {
        randomNum = Math.random()
      }
      const time = new Date().getTime()
      this.randomId = time + Math.ceil(randomNum * 1000000000)
    },
    linkProject(recordChild, editable) {
      // debugger
      const type = this.$route.params.type
      let isReadonly
      if (type === 'done-pages') {
        isReadonly = 'VIEW'
      } else {
        isReadonly = 'EDIT'
      }
      // let mainId = this.$refs.flow.getFieldValue('id')
      let mainId = recordChild.mainId
      if (mainId === undefined || mainId === '' || mainId === null) {
        mainId = this.randomId
      }
      let auditedUnitCode = recordChild.auditedUnitCode
      let id = recordChild.id
      if (recordChild.id === undefined || recordChild.id === null) {
        id = ''
      }
      if (recordChild.auditedUnitCode === undefined || recordChild.auditedUnitCode === null) {
        auditedUnitCode = ''
      }
      const url =
        '/spic-engine-construce-table?projectName=' +
        recordChild.projectName +
        '&auditedUnitName=' +
        recordChild.auditedUnitName +
        '&investDecisionDate=' +
        recordChild.investDecisionDate +
        '&cumulativeInvestment=' +
        recordChild.cumulativeInvestment +
        '&projectCode=' +
        recordChild.projectCode +
        '&commencementDate=' +
        recordChild.commencementDate +
        '&planedProductionDate=' +
        recordChild.planedProductionDate +
        '&mainId=' +
        mainId +
        '&id=' +
        id +
        '&auditedUnitCode=' +
        auditedUnitCode +
        '&isEdit=' +
        isReadonly // 编辑面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          setTimeout(this.getConstruceFind(mainId), 3000)
        }
      })
    },
    //  saveproject(formdata) {
    //       this.isSave = true
    //       const selectedKeys = formdata.processFormData.processFormPropertyValues
    //       selectedKeys.forEach((item) => {
    //         if (item.name === 'paperCode') {
    //           this.$refs.flow.setFieldValue('paperCode', item.value)
    //         } else if (item.name === 'iamWorkPaperMaterialEntityList') {
    //           // this.$refs.flow.setFieldValue('iamWorkPaperMaterialEntityList', JSON.parse(item.value))
    //         }
    //       })
    //     },
    getConstruceFind(projectId) {
      // 获取发现列表
      const params = { projectId: projectId }
      axios({
        url: 'api/xcoa-mobile/v1/spicengineconstruceproject/baseFindBean',
        method: 'post',
        data: params,
      }).then((res) => {
        res.data.forEach((item, index) => {
          item.sortNum = index + 1
        })
        this.$refs.flow.setFieldValue('spicEngineConstruceProjectList', res.data)
      })
    },
    remove() {
      // debugger
      const mainId = this.$refs.flow.getFieldValue('id')
      const childData = this.$refs.flow.getFieldValue('spicEngineConstruceProjectList')
      const idList = []
      const ids = this.$refs.tabaData.selectedRowKeys

      if (!ids || ids.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请至少选中一条数据!',
        })
      } else {
        ids.forEach((item) => {
          idList.push(childData[item].id)
        })
        return new Promise((resolve) => {
          Modal.confirm({
            title: '您确定删除这项内容吗？',
            content: '删除这条数据后，就无法恢复初始的状态。',
            okText: '删除',
            cancelText: '取消',
            okType: 'danger',
            onOk: () => {
              axios({
                url:
                  'api/xcoa-mobile/v1/spicengineconstruceproject/deleteById?ids=' +
                  idList.join(','),
                method: 'post',
              })
                .then(() => {
                  // this.$refs.tabaData.clearSelection()

                  Message.success('删除成功')
                  // this.$refs.tabaData.refresh()
                  this.getConstruceFind(mainId)
                })
                .catch((err) => {
                  const msg = errorUtil.getMessage(err) || '删除失败'
                  Message.error(msg)
                })
                .finally(resolve)
            },
            onCancel: () => {
              resolve()
            },
          })
        })

        // ids.forEach((item) => {
        //   idList.push(childData[item].id)
        // })
        // axios({
        //   url: 'api/xcoa-mobile/v1/spicengineconstruceproject/deleteById?ids=' + idList.join(','),
        //   method: 'post',
        // }).then((res) => {
        //   if (res.data) {
        //     Message.success('删除成功')
        //     this.getConstruceFind(mainId)
        //   }
        // })
      }
    },
    getProject() {
      // debugger
      const data = []
      axios({
        url: 'api/xcoa-mobile/v1/spicengineconstruceproject/all-list',
        method: 'post',
      }).then((res) => {
        if (res.status === 200) {
          res.data.forEach((element) => {
            // this.$refs.tabaData.value.push(element)
            data.push(element)
          })
          if (data.length > 0) {
            var saveButtons = this.$refs.flow.flowData.saveButtons
            var buttonId = ''
            saveButtons.forEach((item, index) => {
              if (item.buttonName === '保存') {
                buttonId = item.buttonId
                // console.log('-------buttonId-', buttonId)
              }
            })
            // Message.warn('自动保存中...')
            const button = {
              attrs: null,
              buttonId: buttonId,
              buttonName: '保存',
              fakeId: 'save',
              rollbackSteps: null,
              type: 'save',
            }
            const oldList = this.$refs.flow.getFieldValue('spicEngineConstruceProjectList')
            // console.log('-------旧数据-', oldList)
            const newList = data
            // console.log('-------新数据 -', newList)
            let list
            if (oldList !== undefined && oldList != null) {
              list = [...oldList, ...newList]
            } else {
              list = newList
            }
            this.$refs.flow.setFieldValue('spicEngineConstruceProjectList', list)
            // console.log('-------结果数据shuju-', list)
            this.$refs.flow.buttonClick(button)
          } else {
            Modal.warning({
              title: '提示',
              content: '没有可生成的数据！',
            })
          }
        }
      })
    },
    initData() {
      const mainId = this.$refs.flow.getFieldValue('id')
      const year = new Date().getFullYear()
      const month = new Date().getMonth() + 1
      if (mainId !== null && mainId !== undefined) {
        this.getConstruceFind(mainId)
      }

      if (mainId === undefined || mainId === '') {
        this.$refs.flow.setFieldValue('title', year + '年' + month + '月' + '工程建设项目')
        this.$refs.flow.setFieldValue('submitMonth', month + '月')
      }
      debugger
      if (
        this.$refs.flow.getFieldValue('submitUnit') === undefined ||
        this.$refs.flow.getFieldValue('submitUnit') === null ||
        this.$refs.flow.getFieldValue('submitUnit') === ''
      ) {
        let userInfo = getUserInfo()
        const vunits = []
        const params = {
          orgId: userInfo.deptId,
        }
        axios({
          url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
          method: 'get',
        }).then((res) => {
          userInfo = res.data
          params.orgId = res.data.id
          axios({
            url: 'api/xcoa-mobile/v1/iamorg/findIamOrg',
            method: 'post',
            params,
          }).then((res) => {
            const deptCode = res.data.orgId
            const deptName = res.data.orgName
            this.rootNode = { code: deptCode, name: deptName, id: res.data.id }
            vunits.push({
              type: 'Group',
              code: deptCode,
              name: deptName,
            })
            this.$refs.flow.setFieldValue('submitUnit', vunits)
          })
        })
      }
    },

    changedept() {
      let deptname = ''
      let deptCode = ''
      const value = this.$refs.flow.getFieldValue('submitUnit')
      if (value) {
        value.forEach((d) => {
          deptname += ',' + d.name
          deptCode += ',' + d.code
        })
        if (deptname !== '') deptname = deptname.substring(1, deptname.length)
        this.$refs.flow.setFieldValue('submitUnitName', deptname)
        if (deptCode !== '') deptCode = deptCode.substring(1, deptCode.length)
        this.$refs.flow.setFieldValue('submitUnitCode', deptCode)
      }
    },
    // validateForm() {
    //   debugger
    // },
    changeUser() {
      let username = ''
      let userCode = ''
      const value = this.$refs.flow.getFieldValue('submitUser')
      if (value) {
        value.forEach((d) => {
          username += ',' + d.name
          userCode += ',' + d.code
        })
        if (username !== '') username = username.substring(1, username.length)
        this.$refs.flow.setFieldValue('submitUserName', username)
        if (userCode !== '') userCode = userCode.substring(1, userCode.length)
        this.$refs.flow.setFieldValue('submitUserCode', userCode)
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.odrForm {
  /* :global .sd-page-title {
     display: none;
   } */
  :global(.child-table-title) {
    display: none;
  }

  .lastTr {
    :global(.ant-form-item-control-wrapper) {
      border: none !important;
    }
  }

  :global(.header_sd-child-table_common) {
    right: 115px !important;
  }

  .btnexcel {
    position: relative;
    top: -5px;
    float: right;

    .batchexcel {
      z-index: 100;
      margin-left: 10px;
    }
    .autoprequeue {
      right: 180px;
      z-index: 100;
    }
    .viewSjjh {
      right: 180px;
      z-index: 100;
    }
  }

  :global(.ant-form-item-label > label) {
    width: 100% !important;
    white-space: normal;
  }
}

.projecttable {
  table {
    border-collapse: collapse;
  }
}

.iam-audit-child-table {
  :global(td.ant-form-item-label) {
    width: 15%;
    padding-right: 20px;
    overflow: auto;
    white-space: normal;
  }

  :global(td.ant-form-item-label::after) {
    position: absolute;
    margin: 0 8px 0 8px;
    content: ':';
  }

  :global(td.ant-form-item-label > label::after) {
    margin: 0;
    content: '';
  }

  :global(td.ant-form-item-control-wrapper) {
    width: 32%;
  }
}
:global(.auditplanformmodalcksjjh) {
  :global(.ant-pagination) {
    display: none;
  }
}

.btnselect {
  position: relative;
  float: right;
  .batchselect {
    z-index: 100;
    margin-right: 30px;
    top: 4px;
  }
}
</style>
