<template>
  <div :class="$style.searchdiv">
    <a-spin :spinning="loading">
      <a-card :class="$style.searchWrap">
        <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="11">
              <a-form-model-item label="账套名称" prop="booksName">
                <a-select
                  v-model="form.booksName"
                  :options="booksOptions"
                  @change="booksNameChange"
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="11">
              <a-form-model-item label="查询期间" prop="searchDate">
                <a-range-picker
                  v-model="form.searchDate"
                  format="YYYY-MM"
                  :mode="datemode"
                  :open="dateopen"
                  @panelChange="handlePanelChange"
                  @change="handleChange"
                  @openChange="openChange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="11">
              <a-form-model-item label="账龄段" prop="aging">
                <a-select v-model="form.aging" :options="agingOptions"> </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="11">
              <a-form-model-item label="币种" prop="currency">
                <a-select v-model="form.currency" :options="currencyOptions" show-search>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="16"> </a-col>
            <a-col :class="$style.searchbutton" :span="8">
              <div class="reportbuttonContent" style="margin-right:15%">
                <a-button @click="handleReset">重置</a-button>
                <a-button type="primary" html-type="submit" @click="submitForm">查询</a-button>
                <a-button type="primary" @click="exportData">导出</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
      <a-card :class="$style.reporttablecardxm">
        <div :class="$style.title"
          ><span :class="['toptitle', $style.toptitle]">账龄分析</span></div
        >
        <!-- <sd-data-table
          :key="tableKey"
          ref="dataTable"
          data-url="api/xcoa-mobile/v1/agingAnalysisController/agingAnalysisByMultiSubjects"
          :columns="columns"
          :row-key="(record, index) => index"
          :process-req="processReq"
          :process-res="processRes"
          :defultpagination-pagesize="10"
          @dataLoaded="dataLoaded"
          @rowClick="rowClick"
        >
        </sd-data-table> -->
        <a-table
          ref="dataTable"
          :key="tableKey"
          :pagination="isSubmit ? pagination : false"
          :columns="columns"
          :row-key="(record) => record.id"
          :data-source="tableData"
          :scroll="{ y: 400 }"
          @change="handleTableChange"
        >
        </a-table>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import { message, Modal } from '@/common/one-ui'
import download from '@/common/services/download'
import iamDmAnalysisServices from './iam-dm-analysis-services'
import components from './_import-components/iam-dm-aging-analysis-import'

export default {
  name: 'IamDmAgingAnalysis',
  metaInfo: {
    title: '账龄分析',
  },
  components: {
    ...components,
  },
  data() {
    return {
      pagination: {
        pageSize: 10,
        total: 100,
      },
      loading: false, // 列表加载中
      tableData: [], // 列表数据
      isSubmit: false, // 是否点了查询
      showTable: false, // 是否显示查询结果
      tableKey: 0,
      booksOptions: [], // 账套名称列表
      agingOptions: [
        { label: '1年', value: '12' },
        { label: '半年度', value: '6' },
        { label: '季度', value: '3' },
        { label: '月度', value: '1' },
      ], // 账龄段
      currencyOptions: [], // 币种
      data: [],
      columns: [],
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 12 },
      },
      dateFormat: 'YYYY',
      form: {
        booksName: '',
        searchDate: [],
        aging: '',
        currency: '',
      },
      rules: {
        booksName: [{ required: true, message: '请选择账套名称', trigger: 'change' }],
        searchDate: [{ required: true, message: '请选择查询期间', trigger: 'change' }],
        aging: [{ required: true, message: '请选择财龄段', trigger: 'change' }],
        currency: [{ required: true, message: '请选择币种', trigger: 'change' }],
      },
      params: {},
      datemode: ['month', 'month'],
      dateopen: false,
    }
  },

  mounted() {
    // 初始化数据字典信息
    this.initDictionaryInfo()
  },
  methods: {
    // 分页选择时，重新加载数据
    handleTableChange(pagination, filters, sorter) {
      this.params.bookdCode = this.form.booksName
      this.params.beginDate = this.form.searchDate[0].format('YYYY-MM')
      this.params.endDate = this.form.searchDate[1].format('YYYY-MM')
      this.params.currencyCode = this.form.currency
      this.params.dateSegmentCount = this.form.aging
      this.params.startPosition = pagination.current - 1
      // 当前页赋值
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.params.maxResults = 10
      this.loadTableData(this.params)
    },
    openChange(status) {
      this.dateopen = status
    },
    handleChange(value) {
      this.form.searchDate = value
    },
    handlePanelChange(value, mode) {
      this.form.searchDate = value
      if (mode[1] === 'date') {
        this.dateopen = false
      }
    },
    fnonloadsum() {
      if (!this.flag) {
        if (document.getElementsByClassName('ant-pagination')) {
          document.getElementsByClassName('ant-pagination')[0].style.display = 'none'
        }
        this.flag = true
      } else {
        if (document.getElementsByClassName('ant-pagination')) {
          document.getElementsByClassName('ant-pagination')[0].style.display = ''
        }
      }
    },
    initDictionaryInfo() {
      // 获取账套名称
      iamDmAnalysisServices.findBookName().then((res) => {
        this.booksOptions = res.data.map((item) => {
          return {
            label: item.BOOK_NAME,
            value: item.BOOK_CODE,
          }
        })
      })
    },
    // 账套名称变化时，获取币种列表
    booksNameChange(item) {
      // 获取币种列表
      iamDmAnalysisServices.findCrrencyCode(item).then((res) => {
        this.currencyOptions = res.data.map((item) => {
          return {
            label: item.CURRENCY_NAME,
            value: item.CURRENCY_CODE,
          }
        })
        this.form.currency = 'RMB'
      })
    },
    dataLoaded(eventData) {
      this.showTable = true
      return eventData
    },
    // 判断账龄段和查询区间的对应关系
    checkAgin() {
      // 将年转化为月，再加上月，计算差值
      let date1 = this.form.searchDate[0].format('YYYY-MM').split('-')
      date1 = parseInt(date1[0]) * 12 + parseInt(date1[1])
      let date2 = this.form.searchDate[1].format('YYYY-MM').split('-')
      date2 = parseInt(date2[0]) * 12 + parseInt(date2[1])

      if (date2 - date1 < parseFloat(this.form.aging) - 1) {
        return false
      } else {
        return true
      }
    },
    submitForm() {
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          // 判断账龄段和查询区间的对应关系
          if (!this.checkAgin()) {
            const text = this.agingOptions.find((item) => {
              return item.value === this.form.aging
            }).label
            Modal.warning({
              title: '提示',
              content: `财龄段为${text}时，查询期间间隔必须大于${this.form.aging}个月`,
            })
            return false
          }
          this.isSubmit = true
          this.params.bookdCode = this.form.booksName
          this.params.beginDate = this.form.searchDate[0].format('YYYY-MM')
          this.params.endDate = this.form.searchDate[1].format('YYYY-MM')
          this.params.currencyCode = this.form.currency
          this.params.dateSegmentCount = this.form.aging
          this.params.startPosition = 0
          this.params.maxResults = 10

          // 重置分页到第1页
          const pager = { ...this.pagination }
          pager.current = 1
          this.pagination = pager
          this.loadTableData(this.params)
        }
      })
    },
    // 加载列表数据
    loadTableData(params) {
      // 获取列表数据
      this.loading = true
      iamDmAnalysisServices.getList(params).then((res) => {
        this.pagination.total = res.data.count
        this.loading = false
        this.columns = [
          {
            title: '序号',
            dataIndex: 'sortNum',
            width: '80px',
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            title: '科目编码',
            dataIndex: 'ACC_CODE',
          },
          {
            title: '科目名称',
            dataIndex: 'ACC_NAME',
          },
        ]

        const tableDataList = []
        res.data.dataList.forEach((data, dataIndex) => {
          const dataJson = {
            id: dataIndex,
            ACC_CODE: data.ACC_CODE,
            ACC_NAME: data.ACC_NAME,
          }
          data.agingAnalysis.forEach((item, index) => {
            if (dataIndex === 0) {
              this.columns.push({
                title: item.segmentName,
                dataIndex: 'agingAmount' + index,
              })
            }
            dataJson['agingAmount' + index] = item.agingAmount
          })
          tableDataList.push(dataJson)
        })

        this.tableData = [...tableDataList]
        this.tableKey++
      })
    },
    processReq(req) {
      req.data = {
        ...req.data,
        bookdCode: this.params.bookdCode,
        beginDate: this.params.beginDate,
        endDate: this.params.endDate,
        currencyCode: this.params.currencyCode,
        dateSegmentCount: this.params.dateSegmentCount,
        pageIndex: req.data.startPosition,
        pageSize: req.data.maxResults,
      }
      return req
    },
    processRes(res) {
      res.total = res.count
      return res
    },
    handleReset() {
      // this.isSubmit = false
      this.$refs.advancedSearchForm.resetFields()
      // 特殊处理，清空字段值
      // this.handlesearch()
    },
    // 导出接口
    exportData() {
      if (this.tableData.length === 0) {
        message.warning('未查询出可导出数据', 1)
        return
      }
      this.loading = true
      iamDmAnalysisServices
        .exportData(this.params)
        .then((data) => {
          const url = URL.createObjectURL(data.data)
          download(url, '财务账龄分析.xls')
          this.loading = false
        })
        .catch(() => {
          message.error('导出失败', 3)
        })
    },
    rowClick(record, { rowIndex, column }) {
      let type = '1'
      if (this.params.dimension === 'domains') {
        type = '2'
      }
      const param = {
        dateStart: this.params.dateStart,
        dateEnd: this.params.dateEnd,
        dimension: this.params.dimension,
        unitIds: "'" + record.UNIT_ID + "'",
        auditedUnitNames: "'" + record.AUDITED_UNIT_NAME + "'",
      }
      if (type === '1') {
        param.columnValue = this.convertAttrName(this.sjlxcolumns, column.dataIndex)
      } else {
        param.columnValue = this.convertAttrName(this.sjycolumns, column.dataIndex)
      }
      // window.open(`#/sd-webflow/done-pages/${record.instId}`)
      const url =
        '#/audit-annualplancompletion-project-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=projectlist'
      window.open(url)
    },
    convertAttrName(columns, name) {
      let names = name.split('_')
      names = names.map((item, index) => {
        if (index === 0) {
          if (item.toLowerCase() === 'sum') {
            return ''
          } else {
            return item.toLowerCase()
          }
        } else {
          return item.substr(0, 1) + item.substr(1).toLowerCase()
        }
      })
      return names.join('')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.title {
  text-align: center;
  .toptitle {
    color: #404040;
    font-weight: bold;
    font-size: 22px;
  }
}

.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%;
  background-color: #f0f2f5;
  :global(.sd-has-table.ant-card) {
    min-height: 50%;
  }
  .reporttablecardxm {
    :global(.ant-table-body) {
      height: auto !important;
      overflow: auto;
      min-height: auto !important;
    }
  }
  :global(.ant-table-placeholder) {
    height: 500px !important;
    :global(.ant-empty-normal) {
      margin-top: 130px;
    }
  }
}
:global(.statistics) {
  :global(.ant-table-wrapper) {
    margin-top: 40px;
  }
}
</style>
