<template>
  <div :class="$style.wrapHeight">
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '203px', top: '60px !important' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="10">
            <a-form-model-item :label="'发生日期'">
              <a-range-picker v-model="formData.happenTime" style="width:100%;" />
            </a-form-model-item>
          </a-col>
          <a-col :span="14">
            <a-form-model-item :label="'\u2003\u2003事件名称'">
              <a-input v-model="formData.eventName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="10">
            <a-form-model-item label="事件类型">
              <sd-select v-model="formData.eventType" :options="eventType" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="14">
            <a-form-model-item :label="'\u2003\u2003事件性质'">
              <sd-select v-model="formData.eventNature" :options="eventNature" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="10">
            <a-form-model-item :label="'处置进展'">
              <sd-select
                v-model="formData.disposalProgress"
                :allow-clear="true"
                :options="disposalProgress"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="14">
            <a-form-model-item :label="'是否重大风险事件'" class="zdfxsj">
              <sd-select
                v-model="formData.isMajorEvent"
                :allow-clear="true"
                :options="isMajorEvent"
              />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <div :class="[$style.btns]">
        <audit-advanced-export
          ref="Export"
          :class-style="[$style.buttonSpacing]"
          :exclebxh="false"
          :expressions="expressions"
          :config-id="231"
          :v-if="false"
        />
      </div>
      <sd-data-table
        ref="riskLossEventTable"
        data-url="api/xcoa-mobile/v1/iam-common/search"
        :row-key="'INST_ID'"
        :projectlist="true"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :process-req="processReq"
        :search-fields="['EVENT_NAME', 'EVENT_TYPE']"
        :filter-expressions="expressions"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import axios from '@/common/services/axios-instance'
import FlowcenterService from '@/flowcenter/flowcenter-service'
import { Modal, message } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import systemManage from '@/system-manage/system-manage'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedExport from '@product/iam/components/audit-advanced-export.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import components from './_import-components/risk-loss-event-list-import'
export default {
  name: 'RiskLossEventList',
  metaInfo: {
    title: '风险损失事件',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    auditAdvancedExport,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      yearArry: [],
      waterMark: systemManage.getFormWaterMark(),
      flag: true,
      recordId: '',
      key: 0,
      searchform: 'searchform',
      formData: {
        happenTime: null,
        eventName: '',
        eventType: null,
        eventNature: null,
        disposalProgress: null,
        isMajorEvent: null,
      },
      eventType: [],
      eventNature: [],
      disposalProgress: [],
      isMajorEvent: [],
      dataUrl: 'api/xcoa-mobile/v1/riskassessment/all-list',
      // ?taskId=' + this.$route.query.taskId,
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '发生日期',
          dataIndex: 'HAPPEN_TIME',
          sdRender: TableColumnTypes.date,
          width: '100px',
          defaultSortOrder: 'descend',
        },
        {
          title: '事件名称',
          dataIndex: 'EVENT_NAME',
          scopedSlots: { customRender: 'islink' },
          width: '100px',
        },
        {
          title: '事件类型',
          dataIndex: 'EVENT_TYPE',
          width: '100px',
        },
        {
          title: '事件性质',
          dataIndex: 'EVENT_NATURE',
          width: '100px',
        },
        {
          title: '责任单位/部门',
          dataIndex: 'RESPONSIBLE_DEPT_NAME',
          width: '180px',
        },
        {
          title: '是否重大风险事件',
          dataIndex: 'IS_MAJOR_EVENT',
          width: '200px',
        },
        {
          title: '损失金额(万元)',
          dataIndex: 'LOSS_AMOUNT',
          width: '180px',
        },
        {
          title: '处置进展',
          dataIndex: 'DISPOSAL_PROGRESS',
          width: '100px',
        },
        {
          title: '填报单位',
          dataIndex: 'FILLING_UNIT_NAME',
          width: '100px',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null,
          callback: this.create,
          index: 1,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
          permission: null,
          callback: (keys) => {
            this.deleteRows(keys)
          },
          index: 3,
        },
        {
          label: '导出',
          id: 'export',
          permission: null,
          callback: (keys) => {
            this.export()
          },
          index: 4,
        },
      ],
      expressions: [],
      formId: 'riskLossEvent',
      visible: false,
      flowStateOptions: [
        { id: '0', name: '起草' },
        { id: '1', name: '审核' },
        { id: '2', name: '结束' },
      ],
    }
  },
  created() {
    this.initDictionaryInfo()
  },
  methods: {
    export() {
      this.$refs.Export.exportdata()
    },
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=LOSS_EVENT_TYPE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.eventType = res.data
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=EVENT_NATURE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.eventNature = res.data
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=DISPOSAL_PROGRESS',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.disposalProgress = res.data
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=IS_MAJOR_EVENT',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.isMajorEvent = res.data
        }
      })
    },
    // 默认且必须的条件
    processReq(req) {
      req.data.formId = 'riskLossEvent'
      return req
    },
    create() {
      const url = '/sd-flow-guide?code=PRODUCT_RISK_LEVENT' // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },
    refreshDataTable() {
      if (this.$refs.riskLossEventTable) {
        this.$refs.riskLossEventTable.clearSelection()
        this.$refs.riskLossEventTable.refresh()
      }
    },
    rowClick(record) {
      let url = ''
      if (record.END_TYPE === 0) {
        url = `/sd-webflow/pages/draft/` + record.INST_ID
      } else {
        url = `/sd-webflow/done-pages/` + record.INST_ID
      }
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) this.refreshDataTable()
      })
    },
    handleSearch() {
      this.expressions = []

      // 发生日期
      if (this.strOrArr(this.formData.happenTime)) {
        if (this.formData.happenTime[0] === null) {
          this.formData.happenTime = null
        } else {
          this.expressions.push({
            dataType: 'long',
            name: 'HAPPEN_TIME',
            op: 'ge',
            longValue: moment(this.formData.happenTime[0])
              .startOf('day')
              .valueOf(),
          })
          this.expressions.push({
            dataType: 'long',
            name: 'HAPPEN_TIME',
            op: 'le',
            longValue: moment(this.formData.happenTime[1])
              .endOf('day')
              .valueOf(),
          })
        }
      }
      // 事件名称
      if (this.formData.eventName) {
        this.expressions.push({
          dataType: 'str',
          name: 'EVENT_NAME',
          op: 'like',
          stringValue: '%' + this.formData.eventName + '%',
        })
      }
      // 事件类型
      if (this.formData.eventType && this.formData.eventType.length > 0) {
        this.expressions.push({
          dataType: 'str',
          name: 'EVENT_TYPE',
          op: 'eq',
          stringValue: this.formData.eventType[0].id,
        })
      }
      // 事件性质
      if (this.formData.eventNature && this.formData.eventNature.length > 0) {
        this.expressions.push({
          dataType: 'str',
          name: 'EVENT_NATURE',
          op: 'eq',
          stringValue: this.formData.eventNature[0].id,
        })
      }
      // 处置进展
      if (this.formData.disposalProgress && this.formData.disposalProgress.length > 0) {
        this.expressions.push({
          dataType: 'str',
          name: 'DISPOSAL_PROGRESS',
          op: 'eq',
          stringValue: this.formData.disposalProgress[0].id,
        })
      }
      // 是否重大风险事件
      if (this.formData.isMajorEvent && this.formData.isMajorEvent.length > 0) {
        this.expressions.push({
          dataType: 'str',
          name: 'IS_MAJOR_EVENT',
          op: 'eq',
          stringValue: this.formData.isMajorEvent[0].id,
        })
      }

      this.expressions = [...this.expressions]
    },

    // 重置
    resetForm() {
      this.formData = {
        happenTime: null,
        eventName: '',
        eventType: null,
        eventNature: null,
        disposalProgress: null,
        isMajorEvent: null,
      }
    },
    // 判断数组或字符串为null或长度为0
    strOrArr(strOrArr) {
      return strOrArr !== null && strOrArr.length > 0
    },
    // 删除数据
    deleteRows(selectedRowKeys) {
      const selecteFlowState = this.$refs.riskLossEventTable.getSelectedRows()
      const currentAccount = getUserInfo().account
      if (selecteFlowState.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      var flages = true
      selecteFlowState.forEach((item) => {
        if (item.CREATOR_ACCOUNT !== currentAccount) {
          Modal.error({
            content: '请选择自己创建的文件',
          })
          flages = false
        }
      })
      if (!flages) {
        return
      }
      let flag = false
      selecteFlowState.forEach((item) => {
        if (item.END_TYPE !== 0) {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
      } else {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除数据后，就无法恢复初始的状态。',
          okText: '删除',
          cancelText: '取消',
          okType: 'danger',
          onOk: () => {
            this.loading = true
            const params = {
              flowCallbackBeanName: 'formBeanCleanerCallBack',
              processInstanceIds: selectedRowKeys.join(','),
            }
            FlowcenterService.fnDarftsDelete(params).then((res) => {
              if (res.status === 200) {
                message.success({ content: '删除成功！' }, 1).then(() => {
                  this.refreshDataTable()
                })
              }
            })
          },
          onCancel: () => {
            // resolve()
          },
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
.btns {
  position: absolute;
  top: 5px;
  right: 0;
  left: 20px;
  z-index: 100;
  width: 50%;
  span {
    color: blue;
  }
}
:global(.zdfxsj) {
  :global(.ant-form-item-label) {
    margin-left: -33px;
  }
}
</style>
