<template>
  <div :class="$style.searchdiv">
    <a-card :class="$style.searchWrap">
      <a-form-model
        ref="advancedSearchForm"
        layout="horizontal"
        :model="form"
        v-bind="formItemLayout"
      >
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="统计日期">
              <a-range-picker v-model="form.timeRange" :time-range.sync="form.timeRange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="统计单位">
              <sd-group-picker v-model="form.Org" :read-only="false" :single="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="案件类型">
              <a-checkbox-group v-model="form.caseType" :options="caseTypeOptions" />
            </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"
                :loading="isLoading"
                @click="submitForm"
                >查询</a-button
              >
              <a-button type="primary" :loading="isLoading" @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>
        <sd-data-table
          ref="exportTable"
          :key="tableKey"
          data-url="api/xcoa-mobile/v1/law-statistics/case-dept"
          :process-req="processReq"
          :process-res="processRes"
          row-key="index"
          :columns="columns"
        ></sd-data-table>
      </div>
    </a-card>
  </div>
</template>

<script>
import { message } from '@/common/one-ui'
import download from '@/common/services/download'
import axios from '@/common/services/axios-instance'
import moment from 'moment'
import LawService from '../law-service'
import components from './_import-components/law-incident-unit-statistics-form-import'

export default {
  name: 'LawIncidentUnitStatisticsForm',
  metaInfo: {
    title: '案发单位统计',
  },
  components: {
    ...components,
  },
  data() {
    return {
      isFirst: true,
      isLoading: false,
      tableKey: 0,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      form: {
        timeRange: [],
        Org: [],
        caseType: [],
      },
      caseTypeOptions: [],
      columns: [
        {
          title: '单位名称',
          dataIndex: 'deptName',
        },
        {
          title: '累计案件数量',
          dataIndex: 'count',
        },
        {
          title: '累计案件金额（元）',
          dataIndex: 'caseAmount',
        },
        {
          title: '累计结案数量',
          dataIndex: 'finishNum',
        },
        {
          title: '累计结案金额（元）',
          dataIndex: 'finishAmount',
        },
        {
          title: '累计减损金额（元）',
          dataIndex: 'loseAmount',
        },
      ],
    }
  },
  created() {
    // 获取案件类型
    // const params = {
    //   buttonExpressions: [],
    //   columns: 'id,name,code,sortNum,status,valueDesc',
    //   expressions: [
    //     {
    //       dataType: 'str',
    //       name: 'keyId',
    //       op: 'eq',
    //       stringValue: '272818597314232320',
    //     },
    //   ],
    //   formId: 'weAppDictValue',
    //   maxResults: 10,
    //   startPosition: 0,
    // }
    LawService.getdict('272818597314232320').then((res) => {
      const dict = [
        {
          label: '全部',
          value: 'all',
          onChange: this.typeChange,
        },
      ]
      res.data.forEach((d) => {
        dict.push({
          label: d.label,
          value: d.value,
          disabled: false,
        })
      })
      this.caseTypeOptions = [...dict]
    })
    // 设置统计日期默认值
    this.form.timeRange = [moment().startOf('year'), moment().endOf('day')]
  },
  methods: {
    // 复选框变化时
    typeChange(e) {
      this.caseTypeOptions.forEach((item) => {
        if (item.value !== 'all') {
          item.disabled = e.target.checked
        }
      })
      if (e.target.checked) {
        this.caseTypeOptions.forEach((item) => {
          if (item.value !== 'all' && !this.form.caseType.includes(item.value)) {
            this.form.caseType.push(item.value)
          }
        })
      } else {
        this.$nextTick().then(() => {
          this.form.caseType = []
        })
      }
    },
    submitForm() {
      this.isLoading = true
      this.isFirst = false
      this.tableKey++
    },
    processReq(req) {
      req.data = {
        startDate: this.form.timeRange[0] ? moment(this.form.timeRange[0]).valueOf() : undefined,
        endDate: this.form.timeRange[1] ? moment(this.form.timeRange[1]).valueOf() : undefined,
        unitIds: this.form.Org[0]?.code,
        caseTypes: this.form.caseType.length > 0 ? this.form.caseType.join(',') : undefined,
      }
      return req
    },
    processRes(res) {
      res.forEach((item, index) => (item.index = index + 1))
      this.isLoading = false
      if (this.isFirst) {
        res.data = []
        res.totalSize = 0
        return res
      }
      res.data = [...res]
      res.totalSize = res.data.length
      return res
    },
    resetForm() {
      this.tableKey++
      this.isFirst = true
      this.form = {
        timeRange: [],
        Org: [],
        caseType: [],
      }
    },
    exportForm() {
      if (this.$refs.exportTable.data.length === 0) {
        return message.warning('未查询到可导出数据', 1)
      }
      // 获取画布信息
      axios({
        method: 'post',
        url: 'api/xcoa-mobile/v1/law-statistics/export-case-dept',
        data: {
          startDate: this.form.timeRange[0] ? moment(this.form.timeRange[0]).valueOf() : undefined,
          endDate: this.form.timeRange[1] ? moment(this.form.timeRange[1]).valueOf() : undefined,
          unitIds: this.form.Org[0]?.code,
          caseTypes: this.form.caseType.length > 0 ? this.form.caseType.join(',') : undefined,
        },
        responseType: 'blob',
      }).then((res) => {
        const url = URL.createObjectURL(res.data)
        download(url, '案发单位统计' + moment(new Date()).format('YYYY-MM-DD HH:mm:ss') + '.xls')
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.emptyecharts {
  width: 600px;
  height: 400px;
  margin: auto auto;
  text-align: center;
  &::after {
    content: '无数据';
    padding-top: 150px;
    display: block;
  }
}
.echarts {
  width: 100%;
  height: 400px;
  margin: auto auto;
  text-align: center;
}
.toptitle {
  color: #404040;
  font-weight: bold;
  font-size: 22px;
  margin-left: calc(50% - 150px);
}

.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: calc(100vh - 270px);
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      overflow: auto;
      min-height: auto !important;
    }
  }
  :global(.ant-table-placeholder) {
    height: auto !important;
  }
}
</style>
