<template>
  <audit-form-top-banner
    :handel-save-form="hasLeaderAuthority === 'true' ? saveForm : null"
    @handelSaveForm="saveForm"
  >
    <div :class="$style.wrapContent">
      <sd-detail-form
        ref="form"
        v-sd-watermark="waterMark"
        page-id="audit/work/projectmanage/account/iamProjectAccount"
        form-id="iamProjectAccount"
        :record-id="recordId"
        :class="$style.form"
        :read-only="hasLeaderAuthority === 'false'"
        @close="close(true)"
        @saved="saved"
        @sdFormReady="
          () => {
            this.initData()
          }
        "
      >
        <template v-slot="{ model, fields }">

        </template>
      </sd-detail-form>
    </div>
  </audit-form-top-banner>
</template>

<script>
import { Message } from 'ant-design-vue'
import moment from 'moment'
import axios from '@/common/services/axios-instance'
import systemManage from '@/system-manage/system-manage'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import AuditAccountService from '@product/iam/audit/work/projectmanage/account/audit-account-service'
import components from './_import-components/audit-portal-blogroll-form-import'

export default {
  name: 'AuditPortalBlogrollForm',
  metaInfo: {
    title: '友情链接表单',
  },
  components: {
    ...components,
    auditFormTopBanner,
  },
  data() {
    return {
      expand: true,
      expandInfo: {
        basic: true,
        amount: true,
        other: true,
        submission: true,
        disclose: true,
        asset: true,
      },
      projectId: '',
      waterMark: systemManage.getFormWaterMark(),
      recordId: this.$route.query.record ? parseInt(this.$route.query.record) : null,
      hasLeaderAuthority: this.$route.query.hasLeaderAuthority,
      childOtherFields: [],
      childOtherColumns: [],
      childDiscloseFields: [],
      childDiscloseColumns: [
        {
          title: '序号',
          dataIndex: 'xh',
          customRender: (text, record, index) => `${index + 1}`,
          width: '30px',
        },
        {
          title: '建议项',
          dataIndex: 'discloseProposal',
        },
        {
          title: '件数',
          dataIndex: 'infoNum',
        },
      ],
      keyDictionary: {
        other: [],
        submission: [],
        disclose: [],
        asset: [],
      },
      keyOptions: {
        other: [],
        submission: [],
        disclose: [],
        asset: [],
      },
    }
  },
  created() {
    const projectId = this.$route.query.projectId
    if (projectId) {
      this.projectId = projectId
    }
  },
  methods: {
    expandChange(areaKey) {
      this.expandInfo[areaKey] = !this.expandInfo[areaKey]
    },
    initData() {
      const id = this.$refs.form.getFieldValue('id')
      this.$refs.form.setFieldValue('projectId', this.projectId)
      if (!id) {
        // 新建获取初始化数据
        AuditAccountService.getProjectInfoById(this.projectId).then((res) => {
          // 获取项目信息
          if (res.data) {
            this.$refs.form.setFieldValue('projectTitle', res.data.projectTitle)
            this.$refs.form.setFieldValue('auditType', res.data.auditType)
            if (res.data.planStartTime)
              this.$refs.form.setFieldValue('planStartTime', moment(res.data.planStartTime))
            if (res.data.planEndTime)
              this.$refs.form.setFieldValue('planEndTime', moment(res.data.planEndTime))
            if (res.data.auditperiodStart)
              this.$refs.form.setFieldValue('auditperiodStart', moment(res.data.auditperiodStart))
            if (res.data.auditperiodEnd)
              this.$refs.form.setFieldValue('auditperiodEnd', moment(res.data.auditperiodEnd))
            if (res.data.auditWorkDay)
              this.$refs.form.setFieldValue('auditWorkDay', parseInt(res.data.auditWorkDay))

            this.$refs.form.setFieldValue('projectPeopleNum', parseInt(res.data.projectPeopleNum))
            this.$refs.form.setFieldValue('projectCost', parseFloat(res.data.projectCost))
          }
        })
      }
      this.$refs.form.formData.pageFormData.pageFieldInfos.forEach((child) => {
        if (child.name === 'iamProjectAssetEntitys') {
          const options = child.attr.dync.find((item) => {
            return item.name === 'assetType'
          })
          this.keyDictionary.asset = options.attr.selectListItem
          if (!id) {
            AuditAccountService.getProblemAmount(this.projectId).then((res) => {
              // 获取项目发现问题涉及金额信息（第一次新建调用该接口，编辑和查看后去子表数据）
              if (res.data) {
                this.keyOptions.asset = res.data.map((item) => {
                  return {
                    assetType: item.assetType,
                    amount: item.amount,
                  }
                })
              }
            })
          } else {
            if (child.value && child.value !== '') {
              this.keyOptions.asset = JSON.parse(child.value)
            } else {
              this.keyOptions.asset = this.keyDictionary.asset.map((item) => {
                return {
                  assetType: item.value,
                }
              })
            }
          }
        } else if (child.name === 'iamProjectDiscloseEntitys') {
          const options = child.attr.dync.find((item) => {
            return item.name === 'discloseProposal'
          })
          this.keyDictionary.disclose = options.attr.selectListItem

          if (child.value && child.value !== '') {
            this.keyOptions.disclose = JSON.parse(child.value)
          } else {
            this.keyOptions.disclose = this.keyDictionary.disclose.map((item) => {
              return {
                discloseProposal: item.value,
              }
            })
          }
        } else if (child.name === 'iamProjectSubmissionEntitys') {
          const options = child.attr.dync.find((item) => {
            return item.name === 'submissionProcess'
          })
          this.keyDictionary.submission = options.attr.selectListItem
          if (child.value && child.value !== '') {
            this.keyOptions.submission = JSON.parse(child.value)
          } else {
            this.keyOptions.submission = this.keyDictionary.submission.map((item) => {
              return {
                submissionProcess: item.value,
              }
            })
          }
        } else if (child.name === 'iamProjectOtherEntitys') {
          const options = child.attr.dync.find((item) => {
            return item.name === 'otherItem'
          })
          this.keyDictionary.other = options.attr.selectListItem
          if (child.value && child.value !== '') {
            this.keyOptions.other = JSON.parse(child.value)
          } else {
            this.keyOptions.other = this.keyDictionary.other.map((item) => {
              return {
                otherItem: item.value,
              }
            })
          }
        }
      })
    },
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PROBLEM_SUGGESTIONS', // 纰漏问题
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.keyOptions.disclose = res.data.map((item) => {
            return {
              id: item.id,
              name: item.name,
              discloseProposal: item.id,
              infoNum: item.infoNum,
            }
          })
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=SUBMISSION_PROCESSING', // 报送处理
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.keyOptions.submission = res.data.map((item) => {
            return {
              id: item.id,
              name: item.name,
              submissionProcess: item.id,
              infoNum: item.infoNum,
            }
          })
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PROJECT_ACCOUNT_OTHERS', // 其他
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.keyOptions.other = res.data.map((item) => {
            return {
              id: item.id,
              name: item.name,
              otherItem: item.id,
              infoNum: item.infoNum,
            }
          })
        }
      })
    },
    countTotalAmount(model) {
      model.totalAmount =
        (model.increaseIncome === undefined ? 0 : model.increaseIncome) +
        (model.saveExpenditure === undefined ? 0 : model.saveExpenditure)
      return model.totalAmount
    },
    saveForm() {
      let data = this.keyOptions.asset
      this.$refs.form.setFieldValue('iamProjectAssetEntitys', data)
      let summary = data.reduce((preItem, curItem) => {
        if (curItem.amount) {
          return preItem + parseFloat(curItem.amount, 10)
        } else {
          return preItem
        }
      }, 0)
      this.$refs.form.setFieldValue('findTotalAmount', summary)

      data = this.keyOptions.disclose
      this.$refs.form.setFieldValue('iamProjectDiscloseEntitys', data)
      summary = data.reduce((preItem, curItem) => {
        if (curItem.infoNum) {
          return preItem + parseFloat(curItem.infoNum, 10)
        } else {
          return preItem
        }
      }, 0)
      this.$refs.form.setFieldValue('totalProposal', summary)

      data = this.keyOptions.submission
      this.$refs.form.setFieldValue('iamProjectSubmissionEntitys', data)
      summary = data.reduce((preItem, curItem) => {
        if (curItem.infoNum) {
          return preItem + parseFloat(curItem.infoNum, 10)
        } else {
          return preItem
        }
      }, 0)
      this.$refs.form.setFieldValue('totalSubmitted', summary)

      data = this.keyOptions.other
      this.$refs.form.setFieldValue('iamProjectOtherEntitys', data)

      this.$refs.form.saveBtnClick()
    },
    saved() {
      Message.success('保存成功', 1).then((res) => {
        this.close(true)
      })
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';

.wrapContent {
  .rangeDate {
    :global(.ant-row .ant-form-item) {
      width: 47.5% !important;
    }
  }

  .rangeDate2 {
    :global(.ant-row .ant-form-item) {
      width: 19.3% !important;
    }
  }

  :global(td.ant-form-item-label) {
    width: 15% !important;
  }
  :global(td.ant-form-item-control-wrapper) {
    width: 35% !important;
  }

  :global(.ant-input-number) {
    width: 100% !important;
  }
}
.first-tr {
  td {
    background: #fff !important;
    border: none !important;
  }
}
.total-tr {
  > td {
    border-top: 0 !important;
    border: none !important;
  }
}
.child-table {
  > td {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  :global(.groupstyle_audit-advanced-group_product) {
    margin-left: 5px;
  }
}
.top-none {
  > td {
    border-top: none !important;
  }
}
</style>
