<template>
  <div :class="$style.auditImplement">
    <a-card :class="$style.conditions">
      <a-form-model
        ref="advancedSearchForm"
        class="ant-advanced-search-form"
        :model="form"
        :rules="rules"
        v-bind="formItemLayout"
      >
        <a-row :gutter="24" :class="$style.antformitem">
          <a-col :span="8">
            <a-form-model-item label="年度" prop="panelYear">
              <a-date-picker
                v-model="form.panelYear"
                format="YYYY"
                mode="year"
                :open="showYearPicker"
                @openChange="
                  (val) => {
                    showYearPicker = val
                  }
                "
                @panelChange="
                  (val) => {
                    form.panelYear = val
                    showYearPicker = false
                  }
                "
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审计机构" prop="unitNames">
              <AuditGroupPicker
                ref="unitNames"
                v-model="form.unitNames"
                :single="false"
                :read-only="false"
                :root-node="rootNode"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <div :class="$style.buttonContent">
              <a-button @click="handleReset">重置</a-button>
              <a-button type="primary" @click="handleAction('serach')">查询</a-button>
              <a-button :loading="exportLoading" type="primary" @click="handleAction('export')"
                >导出</a-button
              >
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <p :class="$style.tableTitle"> 项目执行情况统计 </p>
    <a-card class="reporttablecardxm">
      <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/getProjectExecList"
          @dataLoaded1="dataLoadedsum"
          @rowClick="rowClick"
        >
          <template slot="number" slot-scope="text, record">
            {{ text ? text : '0' }}
          </template>
        </sd-data-table-hj>
      </div>
      <sd-data-table
        ref="dataTable"
        :key="dataKey"
        :process-req="processReq"
        :columns="columns"
        :projectlist="true"
        :defultpagination-pagesize="50"
        data-url="api/xcoa-mobile/v1/iam-statistics/getProjectExecList"
        @fnonloadsum="fnonloadsum"
        @dataLoaded="dataLoaded"
        @rowClick="rowClick"
      >
        <template slot="number" slot-scope="text, record">
          {{ text ? text : '0' }}
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import AuditGroupPicker from '../../components/picker/audit-group-picker.vue'
import components from './_import-components/audit-implement-status-import'
import StatisticsService from './statistics-service'
import { message } from '@/common/one-ui'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import download from '@/common/services/download'

export default {
  name: 'AuditImplementStatus',
  metaInfo: {
    title: '项目执行情况',
  },
  components: {
    ...components,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      form: {
        panelYear: null,
        unitNames: [],
      },
      showYearPicker: false,
      reqData: { dateStart: '3000', unitNames: '' },
      data: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '70px',
        },
        {
          title: '审计机构',
          dataIndex: 'UNIT_NAME',
          scopedSlots: { customRender: 'UNIT_NAME' },
        },
        {
          title: '实际项目数',
          dataIndex: 'REAL_NUM',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '未启动',
          dataIndex: 'TODO_NUM',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '进行中',
          children: [
            {
              title: '小计',
              dataIndex: 'DOING_NUM',
              width: '70px',
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            },
            {
              title: '准备阶段',
              dataIndex: 'PREPARE_NUM',
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            },
            {
              title: '实施阶段',
              dataIndex: 'EXEC_NUM',
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            },
            {
              title: '报告阶段',
              dataIndex: 'REPORT_NUM',
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            },
          ],
        },
        {
          title: '已关闭',
          dataIndex: 'CLOSE_NUM',
          width: '90px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '已归档',
          dataIndex: 'ARCHIVE_NUM',
          width: '90px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '实际完成率',
          dataIndex: 'PERCENT',
        },
      ],
      columnssum: [
        {
          title: '审计机构',
          dataIndex: 'UNIT_NAME',
          scopedSlots: { customRender: 'UNIT_NAME' },
        },
        {
          title: '实际项目数',
          dataIndex: 'REAL_NUM',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '未启动',
          dataIndex: 'TODO_NUM',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '进行中',
          children: [
            {
              title: '小计',
              dataIndex: 'DOING_NUM',
              width: '70px',
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            },
            {
              title: '准备阶段',
              dataIndex: 'PREPARE_NUM',
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            },
            {
              title: '实施阶段',
              dataIndex: 'EXEC_NUM',
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            },
            {
              title: '报告阶段',
              dataIndex: 'REPORT_NUM',
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            },
          ],
        },
        {
          title: '已关闭',
          dataIndex: 'CLOSE_NUM',
          width: '90px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '已归档',
          dataIndex: 'ARCHIVE_NUM',
          width: '90px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '实际完成率',
          dataIndex: 'PERCENT',
        },
      ],
      rules: {
        panelYear: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
        unitNames: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      dataKeysum: 0,
      dataKey: 0,
      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 =
      'realTotal;todoTotal;doingTotal;prepareTotal;execTotal;reportTotal;closeTotal;archiveTotal;percentTotal'
    const arrym = ym.split(';')
    this.hjarr = arrym
  },
  methods: {
    processReq(req, pagination) {
      req.data = {
        dateStart: this.reqData.dateStart,
        unitIds: this.reqData.unitNames,
        maxResults: req.data.maxResults,
        startPosition: req.data.startPosition,
      }
      return req
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
    },
    handleAction(type) {
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          // 处理时间
          this.reqData.dateStart = this.form.panelYear.year() + ''
          // 处理部门
          const arr = []
          this.form.unitNames.forEach((item) => {
            arr.push(`'${item.id}'`)
          })
          this.reqData.unitNames = arr.join(',')
          this.reqData.unitIds = arr.join(',')
          // 调用方法
          switch (type) {
            case 'serach':
              this.handleSearch()
              break
            case 'export':
              this.handleExport()
              break
          }
        }
      })
    },
    handleExport() {
      if (this.$refs.dataTable.data.length === 0) {
        message.warning('未查询出可导出数据', 1)
        return
      }
      this.exportLoading = true
      StatisticsService.exportImplementList(this.reqData).then((data) => {
        const url = URL.createObjectURL(data)
        download(url, '项目执行情况统计表.xls')
        this.exportLoading = false
      })
    },
    handleSearch() {
      this.dataKey++
      this.dataKeysum++
    },

    dataLoaded(res) {
      if (res.data.length) {
        res.data.forEach((item, index) => {
          item.id = index + 1
        })

        this.hjarr.forEach((item) => {
          this.hj[item] = res.respData[item]
        })

        return res
      }
    },
    processReqsum(req, pagination) {
      req.data = {
        dateStart: this.reqData.dateStart,
        unitIds: this.reqData.unitNames,
        maxResults: req.data.maxResults,
        startPosition: req.data.startPosition,
      }
      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
      }
    },
    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)
    },
    rowClick(record, { rowIndex, column }) {
      const param = {
        planYear: this.reqData.dateStart,
        unitIds: "'" + record.UNIT_ID + "'",
      }
      if (record.UNIT_NAME === '总计') {
        param.unitIds = this.form.unitNames
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(',')
      }
      console.log(column)
      if (column.dataIndex === 'TODO_NUM') {
        // 未启动
        param.itemStatus = '01'
      } else if (column.dataIndex === 'DOING_NUM') {
        // 进行中
        param.itemStatus = "'02','03','04'"
      } else if (column.dataIndex === 'PREPARE_NUM') {
        // 准备
        param.itemStatus = '02'
      } else if (column.dataIndex === 'EXEC_NUM') {
        // 实施
        param.itemStatus = '03'
      } else if (column.dataIndex === 'REPORT_NUM') {
        // 报告
        param.itemStatus = '04'
      } else if (column.dataIndex === 'CLOSE_NUM') {
        // 实施
        param.itemStatus = '05'
      } else if (column.dataIndex === 'ARCHIVE_NUM') {
        param.itemStatus = '07'
      } else if (column.dataIndex === 'REAL_NUM') {
        param.itemStatus = "'01','02','03','04','05','07'"
      }

      const url =
        '#/audit-annualplancompletion-project-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=projectimplement'
      window.open(url)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.auditImplement {
  :global(.ant-form-item) {
    margin: 0;
  }
  :global(.ant-select) {
    width: 100%;
  }
  .conditions {
    margin-bottom: 20px;
  }
  .buttonContent {
    padding-top: 6px;
    text-align: right;
    button {
      margin: 0 4px;
    }
  }
  :global(.anticon-setting) {
    display: none;
  }
  .tableTitle {
    padding-top: 16px;
    margin: 0;
    font-size: 22px;
    font-weight: bold;
    color: #404040;
    text-align: center;
    background: white;
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      min-height: auto !important;
      overflow: auto;
    }
  }
  :global(.ant-table-placeholder) {
    height: auto !important;
  }
}
</style>
