<template>
  <div :class="$style.searchdiv">
    <a-card :class="$style.searchWrap">
      <a-form-model
        ref="advancedSearchForm"
        layout="horizontal"
        :model="form"
        v-bind="formItemLayout"
        :rules="rules"
      >
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="年度" prop="year">
              <a-date-picker
                v-model="form.year"
                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>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审计机构" prop="auditOrg">
              <AuditGroupPicker v-model="form.auditOrg" :read-only="false" :root-node="rootNode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <div class="reportbuttonContent">
              <a-button @click="resetForm">重置</a-button>
              <a-button
                style="margin: 0 5px 10px"
                type="primary"
                html-type="submit"
                @click="submitForm"
                >查询</a-button
              >
              <a-button type="primary" :loading="exportLoading" @click="exportForm">导出</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card class="reporttablecardxm">
      <span class="header_sd-header_common"
        ><span :class="['toptitle', $style.toptitle]">年度计划完成情况</span></span
      >
      <div id="hj" style="display: none">
        <sd-data-table-hj
          ref="dataTablehj"
          :key="dataKeysum"
          :process-req="processReqsum"
          :columns="columnssum"
          :projectlist="true"
          :defultpagination-pagesize="50"
          data-url="api/xcoa-mobile/v1/iam-statistics/getPlanCompletionList"
          @dataLoaded1="dataLoadedsum"
          @rowClick="rowClick"
        >
        </sd-data-table-hj>
      </div>
      <sd-data-table
        v-if="params.year !== '' && params.auditOrg !== []"
        :key="dataKey"
        ref="dataTable"
        data-url="api/xcoa-mobile/v1/iam-statistics/getPlanCompletionList"
        :columns="columns"
        :row-key="(record, index) => index"
        :process-req="processReq"
        :projectlist="true"
        :defultpagination-pagesize="50"
        @dataLoaded="dataLoaded"
        @rowClick="rowClick"
        @fnonloadsum="fnonloadsum"
      >
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import AuditGroupPicker from '../../../../components/picker/audit-group-picker.vue'
import auditService from './iam-audit-report-service'
import components from './_import-components/iam-audit-report-annualplancompletion-import'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import download from '@/common/services/download'
import { message } from '@/common/one-ui'
import left from '@/common/components/sd-icon-library/icons/outline/left'
const columns = [
  {
    title: '序号',

    customRender: (text, record, index) => {
      if (record.UNIT_NAME === '总计') {
        return {
          children: '',
        }
      } else {
        return { children: index + 1 }
      }
    },
    width: '80px',
  },
  {
    title: '审计机构',
    dataIndex: 'UNIT_NAME',
  },
  {
    title: '计划内项目数',
    dataIndex: 'PLAN_IN_SUM',
    sdClickable: true,
  },
  {
    title: '计划内取消数',
    dataIndex: 'PLAN_IN_CANCEL',
    sdClickable: true,
  },
  {
    title: '计划外项目数',
    sdClickable: true,
    children: [
      {
        title: '新增',
        dataIndex: 'PLAN_OUT_ADD',
        sdClickable: true,
      },
      {
        title: '取消',
        dataIndex: 'PLAN_OUT_CANCEL',
        sdClickable: true,
      },
    ],
  },
  {
    title: '实际项目数',
    dataIndex: 'REAL_ALL_PROJ',
    sdClickable: true,
  },
  {
    title: '实际完成项目数',
    sdClickable: true,
    children: [
      {
        title: '计划内',
        dataIndex: 'DONE_IN_PROJ',
        sdClickable: true,
      },
      {
        title: '计划外',
        dataIndex: 'DONE_OUT_PROJ',
        sdClickable: true,
      },
    ],
  },
  {
    title: '在审项目数',
    dataIndex: 'DOING_PROJ',
    sdClickable: true,
  },

  {
    title: '计划完成率',
    dataIndex: 'PLAN_DONE_PERC',
  },
  {
    title: '实际完成率',
    dataIndex: 'REAL_DONE_PERC',
  },
]
const columnssum = [
  {
    title: '审计机构',
    dataIndex: 'UNIT_NAME',
  },
  {
    title: '计划内项目数',
    dataIndex: 'PLAN_IN_SUM',
    sdClickable: true,
  },
  {
    title: '计划内取消数',
    dataIndex: 'PLAN_IN_CANCEL',
    sdClickable: true,
  },
  {
    title: '计划外项目数',
    sdClickable: true,
    children: [
      {
        title: '新增',
        dataIndex: 'PLAN_OUT_ADD',
        sdClickable: true,
      },
      {
        title: '取消',
        dataIndex: 'PLAN_OUT_CANCEL',
        sdClickable: true,
      },
    ],
  },
  {
    title: '实际项目数',
    dataIndex: 'REAL_ALL_PROJ',
    sdClickable: true,
  },
  {
    title: '实际完成项目数',
    sdClickable: true,
    children: [
      {
        title: '计划内',
        dataIndex: 'DONE_IN_PROJ',
        sdClickable: true,
      },
      {
        title: '计划外',
        dataIndex: 'DONE_OUT_PROJ',
        sdClickable: true,
      },
    ],
  },
  {
    title: '在审项目数',
    dataIndex: 'DOING_PROJ',
    sdClickable: true,
  },

  {
    title: '计划完成率',
    dataIndex: 'PLAN_DONE_PERC',
  },
  {
    title: '实际完成率',
    dataIndex: 'REAL_DONE_PERC',
  },
]
export default {
  name: 'IamAuditReportAnnualplancompletion',
  metaInfo: {
    title: '年度计划完成情况',
  },
  components: {
    ...components,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      endOpen: false,
      rules: {
        year: [{ required: true, message: '请选择年度', trigger: 'change' }],
        auditOrg: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      dataKey: 0,
      dataKeysum: 0,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      year: null,
      form: {
        year: '',
        auditOrg: [],
      },
      columns,
      columnssum,
      params: {
        year: '',
        auditOrg: [],
      }, // 查询条件
      flag: true,
      hj: {},
      hjarr: [],
      rootNode: {},
    }
  },
  created() {
    let userInfo = getUserInfo()
    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/findIamOrgId',
        method: 'post',
        params,
      }).then((res) => {
        this.id = res.data
        const deptCode = userInfo.id.toString()
        const deptName = userInfo.name
        this.rootNode = { code: deptCode, name: deptName, id: this.id }
      })
    })
  },
  mounted() {
    // 初始化数据字典信息
    const ym =
      'planInTotal;planInCancelTotal;planOutAddTotal;planOutCancelTotal;realAllProjTotal;doneInProjTotal;doneOutProjTotal;doingProjTotal;planDonePercTotal;realDonePercTotal'
    const arrym = ym.split(';')
    this.hjarr = arrym
    this.submitForm()
  },
  methods: {
    dataLoaded(params) {
      const respData = params.respData
      if (params.data.length !== 0) {
        this.hjarr.forEach((item) => {
          this.hj[item] = respData[item]
        })
      }
      console.log(this.hj)
    },
    yearChange(value) {
      this.year = value
      this.form.year = value.format('YYYY')
      if (document.getElementsByClassName('ant-calendar-picker-container').length > 0) {
        document.getElementsByClassName('ant-calendar-picker-container')[0].style.display = 'none'
      }
    },
    submitForm() {
      if (this.flag) {
        this.params = {
          year: moment(new Date()).format('YYYY'),
          auditOrg: [],
        }
        this.dataKey++
        this.flag = false
      } else {
        this.$refs.advancedSearchForm.validate((valid, values) => {
          if (valid) {
            this.params = {
              year: this.form.year,
              auditOrg: this.form.auditOrg,
            }
            this.dataKey++
            this.dataKeysum++
          }
        })
      }
    },
    processReq(req) {
      req.data = {
        ...req.data,
        planYear: this.params.year,
        unitIds: this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(','),
      }
      return req
    },
    processReqsum(req) {
      req.data = {
        ...req.data,
        planYear: this.params.year,
        unitIds: this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(','),
      }
      return req
    },
    dataLoadedsum(res) {
      if (res.data.length) {
        res.data.splice(0, res.data.length)
        const obj = {}
        let j = 0
        this.columns.forEach((item, index) => {
          if (index > 1) {
            if (item.children) {
              item.children.forEach((c, i) => {
                obj[c.dataIndex] = res.respData[this.hjarr[j]]
                j++
              })
            } else {
              obj[item.dataIndex] = res.respData[this.hjarr[j]]
              j++
            }
          }
        })
        obj.id = 1
        obj.UNIT_NAME = '总计'
        res.data.push(obj)
        return res
      }
    },
    resetForm() {
      this.year = null
      this.form = {
        year: '',
        auditOrg: [],
      }
    },
    exportForm() {
      if (this.$refs.dataTable.data.length === 0) {
        message.warning('未查询出可导出数据', 1)
        return
      }
      this.exportLoading = true
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          const params = {
            planYear: this.form.year,
            unitIds: this.form.auditOrg
              .map((item) => {
                return "'" + item.id + "'"
              })
              .join(','),
          }

          auditService
            .exportNDJHData(params)
            .then((data) => {
              const url = URL.createObjectURL(data)
              download(url, '年度计划完成情况导出.xls')
              this.exportLoading = false
            })
            .catch(() => {
              message.error('导出失败')
              this.exportLoading = false
            })
        }
      })
    },
    rowClick(record, { rowIndex, column }) {
      const param = {
        planYear: this.params.year,
        unitIds: "'" + record.UNIT_ID + "'",
        auditType: this.convertAttrName(column.dataIndex),
      }
      if (record.UNIT_NAME === '总计') {
        param.unitIds = this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(',')
      }
      if (column.dataIndex === 'PLAN_IN_SUM') {
        param.auditType = 'planInSum'
      } else if (column.dataIndex === 'PLAN_IN_CANCEL') {
        param.auditType = 'planInCancel'
      } else if (column.dataIndex === 'PLAN_OUT_ADD') {
        param.auditType = 'planOutAdd'
      } else if (column.dataIndex === 'PLAN_OUT_CANCEL') {
        param.auditType = 'planOutCancel'
      } else if (column.dataIndex === 'REAL_ALL_PROJ') {
        param.auditType = 'realAllProj'
      } else if (column.dataIndex === 'DONE_IN_PROJ') {
        param.auditType = 'doneInProj'
      } else if (column.dataIndex === 'DONE_OUT_PROJ') {
        param.auditType = 'doneOutProj'
      } else if (column.dataIndex === 'DOING_PROJ') {
        param.auditType = 'doingProj'
      }
      const url =
        '#/audit-annualplancompletion-project-list?params=' +
        encodeURIComponent(JSON.stringify(param))
      window.open(url)
    },
    convertAttrName(name) {
      let names = name.split('_')
      names = names.map((item, index) => {
        if (index === 0) {
          return item.toLowerCase()
        } else {
          return item.substr(0, 1) + item.substr(1).toLowerCase()
        }
      })
      return names.join('')
    },
    fnonloadsum() {
      setTimeout(() => {
        if (
          document
            .getElementById('hj')
            .getElementsByClassName('ant-table-tbody')[0]
            .getElementsByTagName('tr').length > 0
        ) {
          const obj = document
            .getElementById('hj')
            .getElementsByClassName('ant-table-tbody')[0].firstChild
          obj.firstChild.colSpan = 2
          obj.classList.add('childsum')
          document.getElementsByClassName('ant-table-tbody')[1].appendChild(obj)
        }
      }, 1000)
    },
    handleEndOpenChange(open) {
      this.endOpen = open
    },
  },
}
</script>

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

.search-wrap {
  margin-bottom: $padding-lg;
  :global(.ant-advanced-search-form) {
    padding: 0;
    background: transparent;
    border: none;
  }
  :global .ant-divider-horizontal {
    margin: 10px 0;
  }
}
.searchdiv {
  height: 100%;
  :global(.sd-has-table.ant-card) {
    min-height: 50%;
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      min-height: auto !important;
      overflow: auto;
    }
  }
  :global(.ant-table-placeholder) {
    height: auto !important;
  }
}
.toptitle {
  margin-left: calc(50% - 150px);
  font-size: 22px;
  font-weight: bold;
  color: #404040;
}
</style>
