<template>
  <div :class="$style.wrapHeight">
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{
          height: '170px',
          width: 'calc(100% - 30px) !important',
          margin: 'auto',
          top: '65px !important',
        }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'整改名称'">
              <a-input v-model="formData.rectName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="整改要求编号">
              <a-input v-model="formData.rectCode"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="创建人员">
              <sd-user-picker v-model="formData.creatorName" single></sd-user-picker>
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table
        v-show="flag"
        :key="key"
        ref="recityList"
        data-url="api/xcoa-mobile/v1/iam-common/search"
        row-key="INST_ID"
        :columns="columns"
        :process-req="processReq"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :filter-expressions="expressions"
        :search-fields="['RECT_NAME']"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="open(record)">{{ text }}</a>
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import FlowcenterService from '@/flowcenter/flowcenter-service'
import { getUserInfo } from '@/common/store-mixin'
import { Modal, message } from 'ant-design-vue'
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 auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import iamIcRectifyFeedbackServices from './iam-ic-rectify-require-service'
import components from './_import-components/iam-ic-rectify-require-list-import'
export default {
  name: 'IamIcRectifyRequireList',
  metaInfo: {
    title: '整改要求列表',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      statusList: [
        {
          id: 0,
          name: '起草中',
        },
        {
          id: 1,
          name: '审批中',
        },
        {
          id: 5,
          name: '已结束',
        },
      ],
      waterMark: systemManage.getFormWaterMark(),
      flag: true,
      recordId: '',
      key: 0,
      searchform: 'searchform',
      formData: {
        rectName: '',
        rectCode: '',
        creatorName: [],
      },
      rootNode: {},
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '整改名称',
          dataIndex: 'RECT_NAME',
          scopedSlots: { customRender: 'islink' },
          width: '300px',
        },
        {
          title: '整改要求编号',
          dataIndex: 'RECT_CODE',
          sorter: true,
          defaultSortOrder: 'descend',
        },
        {
          title: '整改计划反馈截止日期',
          dataIndex: 'FEEDBACK_DATE',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '创建人员',
          dataIndex: 'CREATOR_NAME',
        },
        {
          title: '创建日期',
          dataIndex: 'CREATION_TIME',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '当前状态',
          dataIndex: 'FLOW_STATE',
        },
        { title: '当前处理人', dataIndex: 'CURRENT_USER' },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null,
          callback: this.createRecity,
          index: 4,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
          permission: null,
          index: 3,
          callback: (keys) => {
            this.deleteRows(keys)
          },
        },
      ],
      expressions: [],
      isAdmin: true,
    }
  },
  mounted() {
    // // 加载时判断用户权限
    // iamIcRectifyFeedbackServices.fnCheckUserPrem('icRectRequire').then((res) => {
    //   if (!res.data) {
    //     this.isAdmin = false
    //     this.expressions.push({
    //       dataType: 'str',
    //       name: 'CREATOR_ACCOUNT',
    //       op: 'eq',
    //       stringValue: getUserInfo().account,
    //     })
    //   }
    // })
  },
  methods: {
    // 默认且必须的条件
    processReq(req) {
      req.data.formId = 'icRectRequire'
      return req
    },
    createRecity() {
      const url = '/sd-flow-guide?code=PRODUCT_IC_ZGYQ' // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },

    refreshDataTable() {
      if (this.$refs.recityList) {
        this.$refs.recityList.refresh()
      }
    },
    open(record) {
      let openurl = ''
      const loginUser = getUserInfo()
      if (
        (record.FLOW_STATE === '起草') |
        (record.FLOW_STATE === '开始') |
        (record.FLOW_STATE === null)
      ) {
        if (loginUser.name === record.CURRENT_USER) {
          openurl = '/sd-webflow/pages/draft/' + record.INST_ID
        } else {
          openurl = '/sd-webflow/done-pages/' + record.INST_ID
        }
      } else {
        openurl = '/sd-webflow/done-pages/' + record.INST_ID
      }
      crossWindowWatcher.waitForChanged(openurl).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },
    handleSearch() {
      this.expressions = []
      if (!this.isAdmin) {
        this.expressions.push({
          dataType: 'str',
          name: 'CREATOR_ACCOUNT',
          op: 'eq',
          stringValue: getUserInfo().account,
        })
      }
      // 整改名称
      if (this.formData.rectName) {
        this.expressions.push({
          dataType: 'str',
          name: 'RECT_NAME',
          op: 'like',
          stringValue: '%' + this.formData.rectName + '%',
        })
      }
      // 整改编号
      if (this.formData.rectCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'RECT_CODE',
          op: 'like',
          stringValue: '%' + this.formData.rectCode + '%',
        })
      }
      // 创建人员
      if (this.formData.creatorName.length > 0) {
        this.expressions.push({
          dataType: 'str',
          name: 'CREATOR_ACCOUNT',
          op: 'eq',
          stringValue: this.formData.creatorName[0].code,
        })
      }

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

    // 重置
    resetForm() {
      this.formData = {
        rectName: '',
        rectCode: '',
        creatorName: [],
      }
    },
    // 删除数据
    deleteRows(selectedRowKeys) {
      const selectRows = this.$refs.recityList.getSelectedRows()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selectRows.forEach((item) => {
        if (item.END_TYPE !== 0) {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
      } else {
        Modal.confirm({
          title: '你确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          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.$refs.recityList.clearSelection()
                  this.$refs.recityList.refresh()
                  this.loading = false
                })
              }
            })
          },
        })
      }
    },
  },
}
</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%;
    }
  }
}
</style>
