<template>
  <div>
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '170px', left: '20px', top: '60px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'标\u2002\u2002\u2002\u2002题'" prop="title">
              <a-input v-model="formData.title" allow-clear />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item :label="'资讯类型'" prop="informationType">
              <a-select v-model="formData.informationType" :allow-clear="true">
                <a-select-option :value="1"> 图片新闻 </a-select-option>
                <a-select-option :value="2"> 新闻动态 </a-select-option>
                <a-select-option :value="3"> 通知公告 </a-select-option>
                <a-select-option :value="4"> 其他 </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-model-item :label="'编制人员'" prop="creatorName">
              <a-input v-model="formData.creatorName" allow-clear />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item :label="'当前状态'" prop="flowState">
              <a-input v-model="formData.flowState" allow-clear />
            </a-form-model-item>
          </a-col> -->
        </template>
      </audit-advanced-query>
      <a-radio-group
        v-model="radioValue"
        allow-clear
        :class="$style.radioGroup"
        @change="radioOnChange"
      >
        <a-radio :value="1"> 全部 </a-radio>
        <a-radio :value="2"> 待处理 </a-radio>
      </a-radio-group>
      <sd-data-table-ex
        ref="SJZXDataTable"
        :filter-expressions="expressions"
        :columns="columns"
        :actions="actions"
        form-id="iamAuditInformation"
        :data-url="dataurl"
        :search-fields="['title', 'creatorName', 'flowState']"
        show-selection
        :show-advance-query="true"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </div>
        <div slot="islink2" slot-scope="text, record">
          <a @click="rowClick2(record)">{{ text }}</a>
        </div>
        <div slot="islink3" slot-scope="text, record">
          <a v-if="record.flowState === '结束'" @click="rowClick3(record)">阅读情况</a>
        </div>
      </sd-data-table-ex>
    </a-card>
  </div>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import { message, Modal } from 'ant-design-vue'
import PageService from '@/common/services/page-service'
import axios from '@/common/services/axios-instance'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import components from './_import-components/audit-information-list-import'

export default {
  name: 'AuditInformationList',
  metaInfo: {
    title: '工作动态管理',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      radioValue: 1,
      searchform: 'searchform',
      dataurl: 'api/xcoa-mobile/v1/iamauditinformation/all-list',
      expressions: [],
      formData: {
        title: '',
        informationType: null,
        creatorName: '',
        flowState: '',
      },
      formId: 'iamAuditInformation',
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '30px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '标题',
          dataIndex: 'title',
          scopedSlots: { customRender: 'islink' },
          width: '50%',
        },
        {
          title: 'instId',
          dataIndex: 'instId',
          sdHidden: true,
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '发布日期',
          dataIndex: 'finishdate',
          sdRender: TableColumnTypes.date,
          sorter: true,
          defaultSortOrder: 'desc',
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
          scopedSlots: { customRender: 'islink2' },
        },
        {
          title: '当前处理人',
          dataIndex: 'currentUser',
        },
        {
          title: '操作',
          dataIndex: '',
          scopedSlots: { customRender: 'islink3' },
        },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: this.deleteRows,
        },
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: 'create', // 纯前端操作，不需要权限控制
          callback: () => {
            const url = '/sd-flow-guide?code=PRODUCT_IAM_SJZXGL' // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refresh()
              }
            })
          },
        },
      ],
    }
  },
  created() {},
  methods: {
    // 删除数据
    deleteRows(record) {
      const userInfo = getUserInfo()
      const selecteFlowState = this.$refs.SJZXDataTable.getSelectedRows()
      const selectedRowKeys = this.$refs.SJZXDataTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }

      axios({
        url: 'api/xcoa-mobile/v1/iamauditinformation/findHasPermission',
        method: 'post',
      }).then((res) => {
        if (res.data === true) {
          this.flagdelete()
        } else {
          selecteFlowState.forEach((item) => {
            if (item.creatorName !== userInfo.name) {
              Modal.error({
                title: '删除失败，不可删除他人创建的流程！',
              })
            } else {
              this.flagdelete()
            }
          })
        }
      })
    },

    flagdelete() {
      let flag = true
      const rows = this.$refs.SJZXDataTable.getSelectedRows()
      rows.forEach((r) => {
        if (r.endType) {
          if (r.endType !== 0) {
            flag = false
          }
        }
      })
      if (!flag) {
        Modal.error({
          title: '删除失败：存在不是起草状态的数据',
        })
        this.loading = false
      } else {
        const selectedRowKeys = this.$refs.SJZXDataTable.getSelectedRowKeys()
        Modal.confirm({
          title: '你确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            this.loading = true
            const params = {
              ids: selectedRowKeys.join(','),
            }

            PageService.delete(params, this.formId).then((res) => {
              message.success('删除成功')
              if (res.status === 200) {
                this.$refs.SJZXDataTable.clearSelection()
                this.$refs.SJZXDataTable.refresh()
                this.loading = false
              }
            })
          },
        })
      }
    },
    refresh() {
      return this.$refs.SJZXDataTable.refresh(true)
    },
    rowClick(record) {
      console.log(record)
      if (record.flowState === '结束') {
        window.open(`?#/iam-audit-home-three?type=gxjb&id=${record.instId}`)
      } else {
        this.rowClick2(record)
      }
    },
    rowClick3(record) {
      if (record.flowState === '结束') {
        const param = {}
        param.formId = 'entity:iamAuditInformation'
        param.beanId = record.instId
        param.title = record.title
        window.open('#/iam-audit-reader-list?params=' + encodeURIComponent(JSON.stringify(param)))
      }
    },
    rowClick2(record) {
      const userInfo = getUserInfo()
      axios({
        url: 'api/xcoa-mobile/v1/iamauditinformation/findHasPermission',
        method: 'post',
      }).then((res) => {
        if (res.data === true) {
          if (
            record.currentUser === userInfo.name &&
            (record.flowState === '起草') | (record.flowState === '开始')
          ) {
            window.open('#/sd-webflow/pages/draft/' + record.instId)
          } else {
            window.open('#/sd-webflow/done-pages/' + record.instId)
          }
        } else if ((record.flowState === '起草') | (record.flowState === '开始')) {
          window.open('#/sd-webflow/pages/draft/' + record.instId)
        } else {
          window.open('#/sd-webflow/done-pages/' + record.instId)
        }
      })
    },

    radioOnChange(e) {
      if (this.selectedType !== e.target.value) {
        this.selectedType = e.target.value
        if (e.target.value === 1) {
          this.dataurl = 'api/xcoa-mobile/v1/iamauditinformation/all-list'
        } else if (e.target.value === 2) {
          this.dataurl = 'api/xcoa-mobile/v1/iamauditinformation/todo-list'
        }
      }
    },
    // 查询
    handleSearch() {
      this.expressions = []

      // 标题
      if (this.formData.title) {
        this.expressions.push({
          dataType: 'str',
          name: 'title',
          op: 'like',
          stringValue: `%${this.formData.title}%`,
        })
      }
      // 资讯类型
      if (this.formData.informationType) {
        this.expressions.push({
          dataType: 'str',
          name: 'informationType',
          op: 'like',
          stringValue: `%${this.formData.informationType}%`,
        })
      }
      // 编制人员
      if (this.formData.creatorName) {
        this.expressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.formData.creatorName}%`,
        })
      }
      // 当前状态
      if (this.formData.flowState) {
        this.expressions.push({
          dataType: 'str',
          name: 'flowState',
          op: 'like',
          stringValue: `%${this.formData.flowState}%`,
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.radioGroup {
  position: absolute;
  top: 30px;
  left: 20px;
}
</style>
