<template>
  <audit-form-top-banner :class="$style.datarecord">
    <!-- 数据导出 -->
    <template slot="afterbtn">
      <!-- <div :class="$style.editbtn">
         :disabled="!isExport"
        <a-button type="primary" :disabled="!isExport" @click="exportData">数据导出</a-button>
      </div> -->
    </template>
    <SdDetailForm
      ref="docform"
      form-id="iamModelMaintain"
      page-id="audit/maintain/iamModelMaintain"
      :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
      :read-only="true"
      :class="$style.form"
      @close="close(true)"
    ></SdDetailForm>
    <a-form-model
      v-bind="{
        labelCol: { span: 7 },
        wrapperCol: { span: 17 },
      }"
      :model="formSearch"
    >
      <a-row style="margin-bottom: 20px">
        <a-col :span="6">
          <a-form-model-item label="时间" prop="time">
            <a-range-picker v-model="formSearch.timeArr" @change="onChangeTime" />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="单位名称" prop="unitName">
            <!-- <a-input v-model="formSearch.unitName" style="width: 200px" /> -->
            <audit-company-select
              ref="cRelSelect"
              v-model="mainSendUnit"
              :read-only="false"
              :single="true"
            />
          </a-form-model-item>
        </a-col>
        <!-- 搜索，数据导出 -->
        <a-col :span="12" style="padding:3px 0 0 10px;">
          <a-form-model-item>
            <a-button type="primary" @click="initColumns">搜索</a-button>
            <!-- 数据导出 -->
            <a-button type="primary" :disabled="!isExport" @click="exportData">数据导出</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <sd-table
      :columns="columnsDetail"
      :data-source="dataDetail"
      :row-key="(_, index) => index"
      :scroll="{ x: '100%' }"
      :pagination="{ showSizeChanger: true, current: current, pageSize: pageSize, total: total }"
      @change="pageChange"
    ></sd-table>
  </audit-form-top-banner>
</template>

<script>
import components from './_import-components/audit-sq-record-import'
import auditMaintainService from './audit-maintain-service'
import { message, Modal } from 'ant-design-vue'
import download from '@/common/services/download'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner.vue'
import auditCompanySelect from '../report/audit-company-select'
import SdDetailForm from '@/common/components/sd-detail-form.vue'
import sdTable from '@/common/components/sd-table.vue'
export default {
  name: 'AuditSqRecord',
  metaInfo: {
    title: '查看数据',
  },
  components: {
    auditFormTopBanner,
    ...components,
    SdDetailForm,
    auditCompanySelect,
    sdTable,
  },
  data() {
    return {
      // 表单数据
      formSearch: {
        time: [],
        unitName: '',
        bussTimeSt: '',
        bussTimeEd: '',
        timeArr: [],
      },
      mainSendUnit: [],
      // 总页数
      total: 0,
      // 当前页
      current: 1,
      // 每页显示条数
      pageSize: 10,
      expressions: [{ dataType: 'str', name: 'modelId', op: 'eq', stringValue: '' }],
      columns: [
        // modelId,valInfo,creationTime
        {
          title: '模型ID',
          dataIndex: 'modelId',
          key: 'modelId',
          width: 100,
        },
        {
          title: '数据',
          dataIndex: 'valInfo',
          key: 'valInfo',
          scopedSlots: { customRender: 'onData' },
        },
      ],
      isExport: false,
      columnsDetail: [],
      dataDetail: [],
    }
  },
  created() {
    this.initTable()
    const roles = this.$store.state.sd.common.userInfo.default.roles
    this.isExport = roles.map((val) => val.code).includes('G-1_MODEL_JOB_EXPORT')
    this.initColumns()
  },

  methods: {
    // 时间选择
    onChangeTime(time) {
      // this.formSearch.time = time
      // bussTimeSt业务开始时间 bussTimeEd 业务结束时间 时间戳类型
      this.formSearch.bussTimeSt = time[0] ? time[0]._d.getTime() : ''
      this.formSearch.bussTimeEd = time[1] ? time[1]._d.getTime() : ''
    },
    isExpressions() {
      const roles = this.$store.state.sd.common.userInfo.default.roles
      const isViewRole = roles.map((val) => val.code).includes('G-1_REGULAR_EXPORT_ROLE')
      const arr = [
        {
          dataType: 'str',
          name: 'unitName',
          op: 'like',
          stringValue: this.mainSendUnit[0]?.name || '',
        },
        {
          dataType: 'str',
          name: 'bussTimeSt',
          op: 'eq',
          stringValue: this.formSearch.bussTimeSt,
        },
        {
          dataType: 'str',
          name: 'bussTimeEd',
          op: 'like',
          stringValue: this.formSearch.bussTimeEd,
        },
        // roleFlag
      ]
      if (isViewRole) {
        arr.push({
          dataType: 'str',
          name: 'roleFlag',
          op: 'eq',
          stringValue: isViewRole ? '1000' : '0',
        })
      }
      return arr
    },

    pageChange(page) {
      this.current = page.current
      this.pageSize = page.pageSize
      this.initColumns()
    },
    initTable() {
      // 获取基础数据
      this.expressions[0].stringValue = this.$route.query.id
    },
    initColumns() {
      const params = {
        columns: 'modelId,valInfo',
        // 当前页*每页显示条数
        maxResults: this.pageSize === Number.MAX_VALUE ? -1 : this.pageSize,
        startPosition: this.pageSize * (this.current - 1),
        // maxResults: this.pageSize * this.current,
        // // 当前页 -1 *每页显示条数
        // startPosition: (this.current - 1) * this.pageSize,
        expressions: [
          {
            dataType: 'str',
            name: 'modelId',
            op: 'eq',
            stringValue: this.$route.query.id,
          },
          ...this.isExpressions(),
        ],
        buttonExpressions: [],
        formId: 'iamModelJobData',
      }
      auditMaintainService.getBaseData(params).then((res) => {
        if (res.data.data.length === 0) {
          this.dataDetail = []
          this.columnsDetail = []
          return message.warning('暂无数据')
        }
        this.total = res.data.totalSize

        const allField = []
        this.columnsDetail = JSON.parse(res.data.data[0].valInfo || '[]').map((item) => {
          allField.push(item.commit)
          return {
            title: item.commit,
            dataIndex: item.commit,
            width: item.value === 'null' ? '100px' : '240px',
            ellipsis: true,
          }
        })
        this.dataDetail = res.data.data.map((item) => {
          const obj = {}
          allField.forEach((field) => {
            const onfield = JSON.parse(item.valInfo || '[]').find((i) => i.commit === field).value
            obj[field] = onfield !== 'null' ? onfield : ''
          })
          // obj.id = item.questionId
          return obj
        })
      })
    },
    exportData() {
      // 导出数据
      const params = {
        columns: 'modelId,valInfo',
        // 当前页*每页显示条数
        maxResults: this.pageSize === Number.MAX_VALUE ? -1 : this.pageSize,
        startPosition: this.pageSize * (this.current - 1),
        // maxResults: this.pageSize * this.current,
        // // 当前页 -1 *每页显示条数
        // startPosition: (this.current - 1) * this.pageSize,
        expressions: [
          {
            dataType: 'str',
            name: 'modelId',
            op: 'eq',
            stringValue: this.$route.query.id,
          },
          ...this.isExpressions(),
        ],
        buttonExpressions: [],
        formId: 'iamModelJobData',
      }
      auditMaintainService.exportDataTime(params).then((res) => {
        if (res.status === 200) {
          const url = URL.createObjectURL(res.data)
          const filename = res.headers['content-disposition']
          const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
          download(url, decodeURI(fname))
          message.success('导出成功')
        } else {
          Modal.warning({
            title: '提示',
            content: '导出报错，请联系管理员!',
          })
          return false
        }
      })
    },
    close(flag) {
      window.close()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.sqrecord {
  height: 100%;
  padding: 10px 20px 15px 20px;
}
.editbtn {
  display: flex;
  justify-content: flex-end;
  padding-top: 8px;
}
.datarecord {
  :global(.ant-btn:nth-child(2)) {
    margin-left: 10px;
  }
}
.row-height {
  height: calc(100% - 60px);
}
</style>
