<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="sdFormReady"
      >
        <template v-slot="{ model, fields }">
          <table>
            <tr>
              <td style="padding-left:5px;border:none">
                <audit-advanced-group
                  :group-label="'基本信息'"
                  :expand-str="'basic'"
                  @changedClick="expandChange"
                ></audit-advanced-group>
              </td>
            </tr>
          </table>

          <table v-show="expandInfo.basic">
            <tr>
              <!-- 项目名称 -->
              <sd-form-item-td name="projectTitle">
                <span>{{ model.projectTitle }}</span>
              </sd-form-item-td>
              <!-- 审计类型 -->
              <sd-form-item-td name="auditType"></sd-form-item-td>
            </tr>
            <tr :class="$style.rangeDate">
              <sd-form-item-td
                label="项目起止日期"
                :name="['planStartTime', 'planEndTime']"
                :input-props="[{ placeholder: '开始' }, { placeholder: '结束' }]"
              />
              <!-- 项目投入天数 -->
              <sd-form-item-td name="auditWorkDay" :input-props="{ min: 0 }" />
            </tr>
            <tr>
              <!-- 项目组人数（个） -->
              <sd-form-item-td name="projectPeopleNum" :input-props="{ min: 0 }" />
              <!--项目投入人天数(人天) -->
              <sd-form-item-td name="projectPeopleDays" :input-props="{ min: 0 }" />
            </tr>
            <tr>
              <!-- 审计金额（万元） -->
              <sd-form-item-td name="auditAmount" :input-props="{ min: 0 }">
                <a-form-model-item
                  :rules="[
                    {
                      validator: validator,
                      trigger: ['change', 'blur'],
                    },
                  ]"
                  prop="auditAmount"
                >
                  <a-input v-model="model.auditAmount"></a-input>
                </a-form-model-item>
              </sd-form-item-td>
              <!-- 项目费用（万元） -->
              <sd-form-item-td name="projectCost" :input-props="{ min: 0 }">
                <a-form-model-item
                  :rules="[
                    {
                      validator: validator,
                      trigger: ['change', 'blur'],
                    },
                  ]"
                  prop="projectCost"
                >
                  <a-input v-model="model.projectCost"></a-input>
                </a-form-model-item>
              </sd-form-item-td>
            </tr>
            <tr :class="$style.rangeDate2">
              <sd-form-item-td
                label="审计期间"
                :colspan="3"
                :name="['auditperiodStart', 'auditperiodEnd']"
                :input-props="[{ placeholder: '开始' }, { placeholder: '结束' }]"
              />
              <!-- 项目投入天数 -->
            </tr>
          </table>

          <table>
            <tr :class="$style.firstTr">
              <td class="ant-form-item-label ant-form-item-label"></td>
              <td></td>
              <td class="ant-form-item-label ant-form-item-label"></td>
              <td></td>
            </tr>
            <tr :class="$style.totalTr">
              <sd-form-item-td name="totalAmount" :label="null" :colspan="4">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="expand"
                    :expand-str="'amount'"
                    :group-label="'增收节支金额合计'"
                    :count-label="'合计' + countTotalAmount(model) + '万元'"
                    @changedClick="expandChange"
                  >
                  </audit-advanced-group>
                </template>
              </sd-form-item-td>
            </tr>
            <tr v-show="expandInfo.amount">
              <sd-form-item-td name="increaseIncome" :input-props="{ min: 0 }">
                <a-form-model-item
                  :rules="[
                    {
                      validator: validator,
                      trigger: ['change', 'blur'],
                    },
                  ]"
                  prop="increaseIncome"
                >
                  <a-input v-model="model.increaseIncome"></a-input>
                </a-form-model-item>
              </sd-form-item-td>
              <sd-form-item-td name="saveExpenditure" :input-props="{ min: 0 }">
                <a-form-model-item
                  :rules="[
                    {
                      validator: validator,
                      trigger: ['change', 'blur'],
                    },
                  ]"
                  prop="saveExpenditure"
                >
                  <a-input v-model="model.saveExpenditure"></a-input>
                </a-form-model-item>
              </sd-form-item-td>
            </tr>
            <tr :class="$style.childTable">
              <sd-form-item-td name="iamProjectAssetEntitys" :label="null" :colspan="4">
                <template v-slot:read-and-edit="{ editable }">
                  <child-table-input
                    :key-options="keyOptions.asset"
                    :key-dic="keyDictionary.asset"
                    :opt-label="'assetType'"
                    :opt-value="'amount'"
                    :read-only="!editable"
                    :group-label="'涉及金额合计'"
                    :group-sum-template="`合计{{sum}}万元`"
                  ></child-table-input>
                </template>
              </sd-form-item-td>
            </tr>
            <tr :class="[$style.childTable, $style.totalTr]">
              <sd-form-item-td name="iamProjectDiscloseEntitys" :label="null" :colspan="4">
                <template v-slot:read-and-edit="{ editable }">
                  <child-table-input
                    :key-options="keyOptions.disclose"
                    :key-dic="keyDictionary.disclose"
                    :opt-label="'discloseProposal'"
                    :opt-value="'infoNum'"
                    :read-only="!editable"
                    :group-label="'披露的问题并提出相应建议合计（条）'"
                    :group-sum-template="`合计{{sum}}件`"
                  ></child-table-input>
                </template>
              </sd-form-item-td>
            </tr>
            <tr :class="[$style.childTable, $style.totalTr]">
              <sd-form-item-td name="iamProjectSubmissionEntitys" :label="null" :colspan="4">
                <template v-slot:read-and-edit="{ editable }">
                  <child-table-input
                    :key-options="keyOptions.submission"
                    :key-dic="keyDictionary.submission"
                    :opt-label="'submissionProcess'"
                    :opt-value="'infoNum'"
                    :read-only="!editable"
                    :group-label="'报送处理合计'"
                    :group-sum-template="`合计{{sum}}件`"
                  ></child-table-input>
                </template>
              </sd-form-item-td>
            </tr>
            <tr :class="[$style.childTable, $style.totalTr]">
              <sd-form-item-td name="iamProjectOtherEntitys" :label="null" :colspan="4">
                <template v-slot:read-and-edit="{ editable }">
                  <child-table-input
                    :key-options="keyOptions.other"
                    :key-dic="keyDictionary.other"
                    :opt-label="'otherItem'"
                    :opt-value="'infoNum'"
                    :read-only="!editable"
                    :group-label="'其他'"
                  ></child-table-input>
                </template>
              </sd-form-item-td>
            </tr>
            <tr :class="$style.topNone">
              <!-- 编制人员 -->
              <sd-form-item-td name="creatorName" />
              <!-- 编制日期 -->
              <sd-form-item-td name="creationTime" />
            </tr>
            <tr>
              <!-- 备注 -->
              <sd-form-item-td name="remarks" :colspan="3">
                <a-textarea v-model="model.remarks" :rows="3" />
              </sd-form-item-td>
            </tr>
          </table>
        </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 auditAdvancedGroup from '../../../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../../../components/audit-advanced-group-mixins'
import childTableInput from './child-table-input.vue'
import components from './_import-components/audit-account-form-import'

export default {
  name: 'AuditComdocumentForm',
  metaInfo: {
    title: '项目台账',
  },
  components: {
    ...components,
    auditFormTopBanner,
    auditAdvancedGroup,
    childTableInput,
  },
  mixins: [auditAdvancedGroupMixins],
  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]
    },
    sdFormReady() {
      const id = this.$refs.form.formData.pageFormData.pageFieldInfos.find((item) => {
        return item.name === 'id'
      })
      this.id = id.value
      if (!this.id) {
        // 新建获取初始化数据
        AuditAccountService.getProjectInfoById(this.projectId).then((res) => {
          // 获取项目信息
          if (res.data) {
            this.$refs.form.setFieldValue('projectId', this.projectId)
            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 (!this.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 =
        parseFloat(model.increaseIncome === undefined ? 0 : model.increaseIncome) +
        parseFloat(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()
    },
    validator(rule, value, callback) {
      if (!new RegExp(/^([1-9][0-9]*|0)(\.[0-9]{1,6})?$/).test(value)) {
        callback('请输入正数，且小数点后最多保留6位,可空')
      } else {
        callback()
      }
    },
  },
}
</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: none !important;
    border-top: 0 !important;
  }
}
.child-table {
  > td {
    padding-right: 0 !important;
    padding-left: 0 !important;
  }
  :global(.groupstyle_audit-advanced-group_product) {
    margin-left: 5px;
  }
}
.top-none {
  > td {
    border-top: none !important;
  }
}
</style>
