<template>
  <div>
    <a-card :class="$style.surveyCard">
      <audit-advanced-query
        :expand="expand"
        :search-data="surveyFormData"
        :ref-name="searchform"
        :search-style="{ height: '170px', left: '20px', top: '40px !important' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'内控流程分类'" prop="title">
              <a-input v-model="surveyFormData.title" allow-clear />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item :label="'测试人员'" prop="testuser">
              <sd-user-picker
                v-model="surveyFormData.testuser"
                allow-clear
                :single="true"
                @change="changery"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'\u2002\u2002\u2002\u2002当前状态'" prop="status">
              <sd-select
                v-model="surveyFormData.status"
                :allow-clear="true"
                :options="flowStateOptions"
              />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table-ex
        ref="iamIcCrossList"
        form-id="icEvaluationCross"
        page-id="ic/evaluation/cross/icEvaluationCross"
        data-url="api/xcoa-mobile/v1/icevaluationcross/all-list"
        :columns="Columns"
        :filter-expressions="Expressions"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :search-fields="['prcName', 'testUserName', 'prcCode']"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </div>
      </sd-data-table-ex>
      <div :class="[$style.btns]">
        <a-col :span="17" :offset="0">
          <a-radio-group v-model="radioValue" @change="radioOnChange">
            <a-radio :style="radioStyle" :value="'0'">
              全部
            </a-radio>
            <a-radio :style="radioStyle" :value="'1'">
              待处理
            </a-radio>
          </a-radio-group>
          <a-checkbox v-model="checkboxValue" style="margin-left: 15px;" @change="onChange">
            未分配
          </a-checkbox>
        </a-col>
      </div>
    </a-card>
    <!-- <ic-measure-select
      ref="mtxmeasuresel"
      :versionId="versionId"
      :orgId="orgId"
      :orgName="orgName"
      :selecttype="'cross'"
      :selectedKeys="this.measureList"
      @fnqd="fnqd"
    /> -->
    <!-- 选择人员组件 -->
    <div v-show="false">
      <ic-measure-picker
        ref="mtxmeasuresel"
        v-model="measureSelect"
        :version-id="versionId"
        :org-id="orgId"
        :org-name="orgName + '内控矩阵'"
        :selecttype="'cross'"
        :single="false"
        :read-only="false"
        @change="fnqd"
      ></ic-measure-picker>
      <sd-user-picker
        ref="userSelect"
        v-model="selectuserOpt"
        :single="true"
        :read-only="false"
        @change="userChange"
      />
    </div>
  </div>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import { Modal, message } from 'ant-design-vue'
import moment from 'moment'
import axios from '@/common/services/axios-instance'
import TableColumnTypes from '@/common/services/table-column-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableActionTypes from '@/common/services/table-action-types'
import icMeasurePicker from '@product/iam/components/ic-picker/ic-measure-picker.vue'
import auditAdvancedQuery from '../../../components/audit-advanced-query.vue'
import icMeasureSelect from '../../../components/ic-measure-select.vue'
import auditAdvancedQueryMixins from '../../../components/audit-advanced-query-mixins'
import MtxEvaluationService from '../ic-evaluation-service'
import MtxProcessService from '../../mtxprocess/mtx-process-service'
import components from './_import-components/iam-work-cross-list-import'

const Columns = [
  {
    title: '序号',
    dataIndex: 'sortNumber',
    customRender: (text, record, index) => `${index + 1}`,
    width: '80px',
  },
  {
    dataIndex: 'id',
    sdHidden: true,
  },
  { dataIndex: 'instId', sdHidden: true },
  {
    title: '内控流程分类',
    dataIndex: 'prcName',
    // sdClickable: true, // 列内容是否可点击
    scopedSlots: { customRender: 'islink' },
  },
  {
    title: '末级流程分类编号',
    dataIndex: 'prcCode',
    width: '10%',
  },
  {
    title: '测试人员',
    dataIndex: 'testUserName',
    width: '10%',
    sorter: true,
  },
  {
    title: '当前状态',
    dataIndex: 'flowState',
    width: '120px',
  },
  { title: '当前处理人', dataIndex: 'currentUser' },
]
export default {
  name: 'IamWorkCrossList',
  metaInfo: {
    title: '穿行测试底稿',
  },
  components: { ...components, auditAdvancedQuery, icMeasurePicker },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      measureSelect: [],
      measureSellist: [],
      radioStyle: {
        height: '30px',
        lineHeight: '30px',
      },
      checkboxValue: false,
      radioValue: '0',
      radioType: true,
      formId: 'icEvaluationCross',
      planId: this.$root.$route.query.planId,
      Columns,
      searchform: 'searchform',
      surveyFormData: {
        title: '',
        testuser: [],
        status: [],
      },
      Expressions: [
        {
          dataType: 'long',
          name: 'planId',
          op: 'eq',
          longValue: this.$root.$route.query.planId,
        },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          permission: null,
          class: 'batch',
          callback: this.deleteRows,
          index: 3,
        },
      ],
      versionId: '',
      orgId: '',
      orgName: '',
      measureList: [],
      selectuserOpt: [],
      testUserName: '',
      flowStateOptions: [
        { id: '0', name: '起草' },
        { id: '1', name: '审核' },
        { id: '2', name: '结束' },
      ],
    }
  },
  mounted() {
    const planId = this.$route.query.planId
    if (planId) {
      this.planId = planId
    }
    axios({
      url: `api/framework/v1/page/wp/ic/evaluation/plan/icEvaluationPlan?id=` + planId,
    }).then((res) => {
      const unitname = res.data.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'evaluationUnitName'
      )
      const unitid = res.data.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'evaluationUnitId'
      )
      const creatorName = res.data.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'creatorName'
      )
      if (res.data.pageFormData.pageFieldInfos[creatorName].value === getUserInfo().name) {
        this.actions = [
          {
            label: '选择评价范围',
            id: 'new',
            permission: null,
            class: 'ant-btn-primary',
            callback: () => {
              // this.$refs.mtxmeasuresel.showtree()
              if (this.versionId === '') {
                Modal.info({
                  content: '请配置机构对应的内控库',
                })
              } else {
                this.$refs.mtxmeasuresel.openPicker()
              }
            },
          },
          {
            label: '设置测试人',
            id: 'set',
            permission: null,
            class: 'ant-btn-primary',
            callback: () => {
              const ids = this.$refs.iamIcCrossList.getSelectedRowKeys()
              const records = this.$refs.iamIcCrossList.getSelectedRows()
              if (ids.length > 0) {
                // this.$refs.userSelect.openPicker()
                let flag = true
                records.forEach((i) => {
                  if (i.flowState !== '起草') {
                    flag = false
                  }
                })
                if (flag) {
                  this.$refs.userSelect.openPicker()
                } else {
                  Modal.info({
                    content: '请选择起草的文件',
                  })
                }
              } else {
                Modal.info({
                  content: '请选择需要设置的文件',
                })
              }
            },
          },
        ].concat(this.actions)
      }
      const params = {
        orgId: res.data.pageFormData.pageFieldInfos[unitid].value,
        moduleId: 'icMtxVersion',
      }
      this.orgName = res.data.pageFormData.pageFieldInfos[unitname].value.toString()
      axios({
        url: 'api/xcoa-mobile/v1/iamorg/findIamOrgId',
        method: 'post',
        params,
      }).then((res) => {
        if (res.data) {
          this.orgId = res.data.toString()
          MtxProcessService.getversion(this.orgId).then((res) => {
            if (res.data.id) {
              this.versionId = res.data.id.toString()
            }
          })
        }
      })
    })
    this.fngetlist()
  },
  methods: {
    // 重置
    resetForm() {
      this.surveyFormData.testuser = []
      this.surveyFormData.status = []
    },
    radioOnChange(e, info) {
      this.radioValue = e.target.value
      this.radioType = true
      this.Expressions.forEach((item) => {
        if (item.name === 'pending') {
          item.stringValue = this.radioValue
          this.radioType = false
        }
      })

      if (this.radioType) {
        this.Expressions.push({
          dataType: 'str',
          name: 'pending',
          op: 'eq',
          stringValue: this.radioValue,
        })
      }
      this.Expressions = [...this.Expressions]
      this.$refs.iamIcCrossList.clearSelection()
    },
    onChange(e) {
      const index = this.Expressions.findIndex(
        (i) => i.name === 'testUserName' && i.op === 'is_null'
      )
      if (e.target.checked) {
        // 未分配
        this.checkboxValue = true
        if (index === -1) {
          this.Expressions.push({
            dataType: 'str',
            name: 'testUserName',
            op: 'is_null',
          })
        }
      } else {
        this.checkboxValue = false
        if (index > -1) {
          this.Expressions.splice(index, 1)
        }
      }
      this.Expressions = [...this.Expressions]
      this.$refs.iamIcCrossList.clearSelection()
    },
    fngetlist() {
      this.measureList = []
      this.measureSellist = []
      MtxEvaluationService.getAllcrossLids(this.planId).then((data) => {
        if (data !== '') {
          if (typeof data === 'number') {
            this.measureList = [data]
          } else {
            this.measureList = data.split(',')
          }
          const obj = []
          this.measureList.forEach((i) => {
            const arr = i.split('$')
            obj.push({
              id: parseInt(arr[0]),
              code: arr[0].toString(),
              text: arr[1],
            })
          })
          this.measureSellist = obj
          this.measureSelect = obj
        } else {
          this.measureSelect = []
        }
      })
    },
    fnqd(data) {
      const ids = []
      data.forEach((i) => {
        let id = i.id.toString()
        if (id.indexOf('1000') > -1) {
          id = id.substring(4, id.length)
        }
        if (this.measureSellist.length > 0) {
          if (this.measureSellist.findIndex((si) => si.id.toString() === i.id.toString()) === -1) {
            ids.push(id)
          }
        } else {
          ids.push(id)
        }
      })
      MtxEvaluationService.savecross(this.planId, ids).then((data) => {
        if (data) {
          message.success({ content: '处理成功！' }, 1).then(() => {
            this.fngetlist()
            this.refresh()
          })
        }
      })
    },
    deleteRows() {
      const selectedRows = this.$refs.iamIcCrossList.getSelectedRows()
      if (selectedRows.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selectedRows.forEach((item) => {
        if (item.endType !== 0) {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
        return
      }
      const ids = []
      const instIds = []
      selectedRows.forEach((item) => {
        if (item.instId === '' || item.instId === null) {
          ids.push(item.id)
        } else {
          instIds.push(item.instId)
        }
      })

      Modal.confirm({
        title: '您确定删除这项内容吗？',
        content: '删除数据后，就无法恢复初始的状态。',
        okText: '删除',
        cancelText: '取消',
        okType: 'danger',
        onOk: () => {
          const params = {
            ids: ids.join(','),
            instIds: instIds.join(','),
          }
          MtxEvaluationService.delete(params, this.formId).then((res) => {
            if (res.status === 200) {
              message.success({ content: '删除成功！' }, 1).then(() => {
                this.fngetlist()
                this.refresh()
              })
            }
          })
        },
      })
    },
    userChange(values) {
      const ids = this.$refs.iamIcCrossList.getSelectedRowKeys()
      const accout = values[0].code
      MtxEvaluationService.setCrossTestor(accout, ids).then((data) => {
        if (data) {
          message.success({ content: '处理成功！' }, 1).then(() => {
            this.selectuserOpt = []
            this.refresh()
          })
        }
      })
    },
    changery(values) {
      this.testUserName = ''
      values.forEach((element) => {
        this.testUserName = element.name
      })
    },
    moment,
    rowClick(record) {
      if (record.instId) {
        let url = ''
        if ((record.flowState === '起草') | (record.flowState === '开始')) {
          const curuser = getUserInfo()
          if (record.testUserName === curuser.name) {
            url = `/sd-webflow/pages/draft/` + record.instId
          } else {
            // message.info('当前人无权限打开该待办', 1)
            url = `/sd-webflow/done-pages/` + record.instId
          }
        } else {
          url = `/sd-webflow/done-pages/` + record.instId
        }
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) this.refresh()
        })
      } else {
        Modal.confirm({
          title: '提示',
          content: '请先分配测试人员！',
          okText: '确定',
          okType: '取消',
        })
      }
    },
    refresh() {
      if (this.$refs.iamIcCrossList) {
        this.$refs.iamIcCrossList.clearSelection()
        this.$refs.iamIcCrossList.refresh()
      }
    },
    handleSearch() {
      this.Expressions = []
      this.Expressions.push({
        dataType: 'long',
        name: 'planId',
        op: 'eq',
        longValue: this.$root.$route.query.planId,
      })
      // 全部 待处理
      if (this.radioValue === '1') {
        this.Expressions.push({
          dataType: 'str',
          name: 'pending',
          op: 'eq',
          stringValue: this.radioValue,
        })
      }
      // 未分配
      if (this.checkboxValue === true) {
        this.Expressions.push({
          dataType: 'str',
          name: 'testUserName',
          op: 'is_null',
        })
      }
      if (this.surveyFormData.title) {
        this.Expressions.push({
          dataType: 'str',
          name: 'prcName',
          op: 'like',
          stringValue: `%${this.surveyFormData.title}%`,
        })
      }
      // 住所
      if (this.surveyFormData.testuser.length > 0) {
        this.Expressions.push({
          dataType: 'str',
          name: 'testUserName',
          op: 'like',
          stringValue: `%${this.testUserName}%`,
        })
      }
      // 状态
      if (this.surveyFormData.status.length > 0) {
        this.Expressions.push({
          dataType: 'str',
          name: 'flowState',
          op: 'like',
          stringValue: this.surveyFormData.status[0].name,
        })
      }
      // this.expand = false
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.sjfxTable {
  :global .ant-table-column-title {
    white-space: normal;
  }
  :global(.ant-table-body) {
    overflow-x: scroll !important;
  }

  :global(.ant-table-empty) {
    :global(.ant-table-body) {
      overflow-x: scroll !important;
    }
  }
}
.survey-card {
  margin-top: -7px;
}
.btns {
  position: absolute;
  top: 0;
  right: 0;
  left: 20px;
  z-index: 100;
  width: calc(40%);
  span {
    color: blue;
  }
}
</style>
