<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <iam-audit-frame-tree
        ref="frametree"
        :key="treekey"
        :draggable="false"
        :checkable="false"
        :createnewframe="false"
        :is-show-item="false"
        :frame-name="frameName"
        @treeSelect="treeSelectframe"
        @treeinit="treeinit"
        @createframe="createframe"
        @changeframe="changeframe"
      ></iam-audit-frame-tree>

      <div :class="$style.rightcard">
        <a-card>
          <!-- 高级搜索组件 -->
          <audit-advanced-query
            :expand="expand"
            :search-data="formData"
            :ref-name="searchform"
            :search-style="{
              height: '170px',
              left: '20px',
              top: '45px !important',
              width: 'calc(100% - 5px) !important',
              margin: 'auto',
            }"
            :search-fun="handleSearch"
            @searchedClick="searchedClick"
            @resetForm="resetForm"
          >
            <template>
              <a-col :span="12">
                <a-form-model-item label="底稿名称" prop="paperTitle">
                  <a-input v-model="formData.paperTitle" allow-clear />
                </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 /> -->
                  <sd-user-picker
                    ref="createnameSelect"
                    v-model="formData.creatorName"
                    :single="true"
                    :read-only="false"
                    @change="changery"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="当前状态" prop="flowState">
                  <sd-select
                    v-model="formData.flowState"
                    :allow-clear="true"
                    :options="flowStateOptions"
                  />
                </a-form-model-item>
              </a-col>
            </template>
          </audit-advanced-query>
          <sd-data-table-ex
            ref="auditOperatePaperTable"
            form-id="iamWorkPaper"
            page-id="audit/work/operate/paper/iamWorkPaper"
            :columns="columns"
            :actions="actions"
            :show-advance-query="true"
            :search-fields="['paperTitle']"
            show-selection
            :filter-expressions="expressions"
            @searchbtnClick="searchbtnClick"
            @tableDataLoaded="tableDataLoaded"
          >
            <div slot="islink" slot-scope="text, record">
              <a class="part-time">
                <span>
                  <a-spin v-if="pending.includes(record.id)">
                    <a-icon slot="indicator" type="loading" :class="$style.submitStatus" />
                  </a-spin>
                  <a-icon
                    v-if="batchSubmitSucceed.includes(record.id)"
                    type="check-circle"
                    :class="[$style.submitStatus, $style.success]"
                  />
                  <a-tooltip
                    v-if="batchsubmitFailed.map((item) => item.id).includes(record.id)"
                    :title="batchsubmitFailed.find((item) => item.id === record.id).message"
                  >
                    <a-icon type="close-circle" :class="[$style.submitStatus, $style.error]" />
                  </a-tooltip>
                </span>
              </a>
              <a :title="text" @click="rowClick(record)">{{
                text === '' || text === null ? '[无标题]' : text
              }}</a>
            </div>
            <div slot="opt" slot-scope="text, record" :class="$style.operatecol">
              <span v-for="(bt, index) in buttonsfortable" :key="index">
                <a-button
                  v-if="
                    (bt.stat === '' || bt.stat === record.flowState) &&
                    (bt.showCondition === '' ||
                      (bt.showCondition !== '' && record[bt.showCondition]))
                  "
                  type="link"
                  size="small"
                  :title="bt.label"
                  @click="optbuttonClick(bt.id, record)"
                >
                  <sd-icon :type="bt.icontype" :theme="bt.theme" />
                </a-button>
              </span>
            </div>
          </sd-data-table-ex>
          <div v-show="false">
            <sd-user-picker
              ref="assignTeamLeader"
              v-model="mainSendUnit"
              :single="true"
              :read-only="false"
              @change="change"
            />
          </div>
        </a-card>
      </div>
    </div>

    <AuditOperatePaperKjModel
      :modal-papervisible="modalPapervisible"
      :project-id="projectId"
      :class-id="catalogId"
      :change="changemodalPapervisible"
      :refresh="refresh"
    />
    <a-modal
      :title="'请选择'"
      :visible="modalPapertreevisible"
      destroy-on-close
      :mask-closable="false"
      :body-style="{
        padding: 0,
      }"
      :width="'700px'"
      :class="$style.operatemodalpaper"
      @ok="handletreeOk"
      @cancel="handletreeCancel"
    >
      <div :class="$style.mattersDiv">
        <iam-audit-frame-tree
          ref="frametree"
          :key="treekey"
          :draggable="false"
          :checkable="false"
          :createnewframe="false"
          :is-show-item="false"
          :frame-name="frameName"
          @treeSelect="modaltreeSelect"
          @treeinit="treeinit"
          @createframe="createframe"
          @changeframe="changeframe"
        />
      </div>
    </a-modal>
    <div :class="[$style.btns]">
      <audit-advanced-import
        ref="import"
        :config-id="'111'"
        :table-id="'list'"
        :relevant-column="parseFloat(projectId)"
        :class-style="[$style.buttonSpacing]"
        :v-if="false"
        @importfromfileAfter="after"
      >
      </audit-advanced-import>
    </div>
  </div>
</template>

<script>
import { Modal, message } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import download from '@/common/services/download'
import axios from '@/common/services/axios-instance'
import errorUtil from '@/common/services/error-util'
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 openAsTrustId from '@/common/services/open-as-trust-id'
import AuditProjectuserService from '@product/iam/audit/work/projectuser/audit-projectuser-service'
import auditAdvancedImport from '../../../../components/audit-advanced-import.vue'
import auditAdvancedGroupMixins from '../../../../components/audit-advanced-group-mixins'
import iamAuditFrameTree from '../../preparation/frame/iam-audit-frame-tree.vue'
import auditAdvancedQuery from '../../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../../components/audit-advanced-query-mixins'
import AuditOperatePaperKjModel from './audit-operate-paper-kj-model.vue'
import AuditOperatePaperService from './audit-operate-paper-service'
import components from './_import-components/audit-operate-paper-list-import'

export default {
  name: 'AuditOperatePaperList',
  metaInfo: {
    title: '工作底稿列表',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    iamAuditFrameTree,
    AuditOperatePaperKjModel,
    auditAdvancedImport,
  },
  mixins: [auditAdvancedGroupMixins, auditAdvancedQueryMixins],
  data() {
    return {
      // 高级搜索用
      pending: [],
      batchSubmitSucceed: [],
      batchsubmitFailed: [],
      expand: false,
      // showflag: false,
      searchform: 'searchform',
      formData: {
        paperTitle: '',
        flowState: '',
        creatorName: '',
      },
      treekey: 0,
      frameName: null, // 默认展示审计框架下拉框名称
      mainSendUnit: [],
      changeeditorprojectId: null,
      key: 0,
      treeData: [],
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '底稿名称',
          dataIndex: 'paperTitle',
          scopedSlots: { customRender: 'islink' },
          width: '40%',
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
        {
          title: '底稿编号',
          dataIndex: 'paperCode',
          width: '30%',
          defaultSortOrder: 'descend',
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
          width: '100px',
        },
        {
          title: '编制人员code',
          dataIndex: 'creatorAccount',
          sdHidden: true,
        },
        { dataIndex: 'findNum', title: '审计发现数量', width: '150px' },
        { dataIndex: 'instId', title: '流程ID', sdHidden: true },
        { dataIndex: 'flowState', title: '当前状态', width: '100px' },
        {
          title: '当前处理人',
          dataIndex: 'nowUser',
          width: '120px',
        },
        {
          title: '操作',
          dataIndex: 'id',
          scopedSlots: { customRender: 'opt' },
          width: '120px',
        },
        { dataIndex: 'nowUserAccount', sdHidden: true },
        { dataIndex: 'canChange', sdHidden: true },
        { dataIndex: 'endType', sdHidden: true },
        { dataIndex: 'itemId', sdHidden: true },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null, // 纯前端操作，不需要权限控制
          // permission: 'iamOperatePaperForm-create', // 纯前端操作，不需要权限控制
          callback: this.createOperatePaper,
        },
        {
          label: '导入',
          id: 'importItem',
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.$refs.import.showImportPanel()
          },
        },
        {
          label: '导出',
          id: 'exportItem',
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.exportPaperExcel()
          },
        },
        {
          label: '导出word',
          id: 'exportwordItem',
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            const selectedRowKeys = this.$refs.auditOperatePaperTable.getSelectedRowKeys()
            if (selectedRowKeys.length === 0) {
              Modal.warning({
                title: '提示',
                content: '请选择需要导出的工作底稿!',
              })
            }
            if (selectedRowKeys.length > 1) {
              Modal.warning({
                title: '提示',
                content: '一次只能选择一个工作底稿!',
              })
            }
            if (selectedRowKeys.length === 1) {
              axios({
                url: 'api/xcoa-mobile/v1/iamworkpaperprograme/paperWord/61/' + selectedRowKeys[0],
                method: 'get',
                responseType: 'blob',
              }).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))
                }
              })
            }
          },
        },

        {
          label: '批量提交',
          id: 'msubmit',
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.allsubmit()
          },
        },
        {
          label: '复制其他项目底稿',
          id: 'copyotherpaper',
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            if (this.catalogId != null) {
              this.modalPapervisible = true
            } else {
              Modal.confirm({
                title: '请先选择分类',
                content: '请先选择分类。',
                okText: '确定',
                cancelText: '取消',
                okType: 'danger',
              })
            }
          },
        },
        {
          label: '变更分类',
          id: 'auditMattersCatalog',
          permission: null,
          callback: () => {
            this.openbgfl()
            // const url = '/sd-frame/audit-matters-catalog' // 新页面要打开的路由地址
            // openAsTrustId(url, null)
          },
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.batch,
          permission: null,
          callback: () => {
            this.linkToDelete()
          },
        },
      ],
      expressions: [
        {
          dataType: 'long',
          name: 'projectId',
          op: 'eq',
          longValue: Number(this.$route.query.projectId),
        },
      ],
      projectexpressions: {
        dataType: 'long',
        name: 'projectId',
        op: 'eq',
        longValue: Number(this.$route.query.projectId),
      },
      frameexpressions: {},
      catalogId: null,
      catalogName: '',
      modalcolumns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '底稿名称',
          dataIndex: 'paperTitle',
        },
      ],
      selectedKeys: ['0'],
      modalPapervisible: false,
      modalPapertreevisible: false,
      modalchangeselectId: '',
      treeselectId: '',
      projectId: '',
      frameId: '',
      buttonsfortable: [
        {
          label: '变更',
          id: 'change',
          showCondition: 'canChange',
          stat: '',
          icontype: 'sd-audit-setprojectleader',
          theme: 'fill',
        },
        {
          label: '重新起草',
          id: 'restart',
          showCondition: '',
          stat: '结束',
          icontype: 'sd-audit-restart',
          theme: 'fill',
        },
      ],
      role: [],
      flowStateOptions: [],
      createName: '',
      // 导出专用id数组
      exportIds: [],
      editflag: true,
    }
  },
  created() {
    // this.addExpression()
  },

  mounted() {
    this.isShowBtn()
    const projectId = this.$route.query.projectId
    if (projectId) {
      this.projectId = projectId
    }
    AuditOperatePaperService.fngetrole(projectId).then((res) => {
      this.role = res.data
      // 控制actions
    })
    // 初始化数据字典信息
    this.initDictionaryInfo()
  },
  methods: {
    // 查看当前登录人是否项目成员，如果同时是项目阅读人员，取最大权限（项目成员权限）
    inProjectUser(userList) {
      var isProjectUser = false
      userList.map((item) => {
        if (item.userAccount === getUserInfo().account) {
          isProjectUser = true
          return isProjectUser
        }
      })
      return isProjectUser
    },
    // 按钮展示条件梳理： 禅道bug22279需要，关闭项目后各阶段都不能再新建（包括其他操作按钮）
    // 所有角色都有新建 编辑 重新起草 查看 导出 删除的权限
    // 项目组长、项目副组长能删除所有的底稿 其他角色只能删除自己的
    isShowBtn() {
      const projectId = this.$route.query.projectId
      axios({
        url: `api/xcoa-mobile/v1/iamauditproject/getProjectInfoById?id=` + projectId,
        method: 'get',
      }).then((res) => {
        if (res.data) {
          const itemStatus = res.data.itemStatus
          const readAuthorityCodes = res.data.readAuthorityCodes
          const userList = res.data.iamProjectUserList
          var isProjectUser = this.inProjectUser(userList)
          AuditOperatePaperService.fngetrole(projectId).then((res) => {
            const datas = res.data
            if (['05', '06', '07'].includes(itemStatus)) {
              this.actions = []
            } else {
              if (
                readAuthorityCodes != null &&
                readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
                !isProjectUser
              ) {
                this.actions = []
              } else {
                // if (datas.length === 1 && datas[0] === '05') {
                //   this.actions = [
                //     {
                //       label: '导出',
                //       id: 'exportItem',
                //       permission: null, // 纯前端操作，不需要权限控制
                //       callback: () => {
                //         this.exportPaperExcel()
                //       },
                //     },
                //     {
                //       label: '导出word',
                //       id: 'exportwordItem',
                //       permission: null, // 纯前端操作，不需要权限控制
                //       callback: () => {
                //         const selectedRowKeys = this.$refs.auditOperatePaperTable.getSelectedRowKeys()
                //         if (selectedRowKeys.length === 0) {
                //           Modal.warning({
                //             title: '提示',
                //             content: '请选择需要导出的工作底稿!',
                //           })
                //         }
                //         if (selectedRowKeys.length > 1) {
                //           Modal.warning({
                //             title: '提示',
                //             content: '一次只能选择一个工作底稿!',
                //           })
                //         }
                //         if (selectedRowKeys.length === 1) {
                //           axios({
                //             url:
                //               'api/xcoa-mobile/v1/iamworkpaperprograme/paperWord/61/' +
                //               selectedRowKeys[0],
                //             method: 'get',
                //             responseType: 'blob',
                //           }).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))
                //             }
                //           })
                //         }
                //       },
                //     },
                //   ]
                // } else {
                //   this.actions = [
                //     {
                //       label: '新建',
                //       id: 'new',
                //       type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
                //       permission: null, // 纯前端操作，不需要权限控制
                //       // permission: 'iamOperatePaperForm-create', // 纯前端操作，不需要权限控制
                //       callback: this.createOperatePaper,
                //     },
                //     {
                //       label: '导出',
                //       id: 'exportItem',
                //       permission: null, // 纯前端操作，不需要权限控制
                //       callback: () => {
                //         this.exportPaperExcel()
                //       },
                //     },
                //     {
                //       label: '导出word',
                //       id: 'exportwordItem',
                //       permission: null, // 纯前端操作，不需要权限控制
                //       callback: () => {
                //         const selectedRowKeys = this.$refs.auditOperatePaperTable.getSelectedRowKeys()
                //         if (selectedRowKeys.length === 0) {
                //           Modal.warning({
                //             title: '提示',
                //             content: '请选择需要导出的工作底稿!',
                //           })
                //         }
                //         if (selectedRowKeys.length > 1) {
                //           Modal.warning({
                //             title: '提示',
                //             content: '一次只能选择一个工作底稿!',
                //           })
                //         }
                //         if (selectedRowKeys.length === 1) {
                //           axios({
                //             url:
                //               'api/xcoa-mobile/v1/iamworkpaperprograme/paperWord/61/' +
                //               selectedRowKeys[0],
                //             method: 'get',
                //             responseType: 'blob',
                //           }).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))
                //             }
                //           })
                //         }
                //       },
                //     },
                //     {
                //       label: '删除',
                //       id: 'delete',
                //       type: TableActionTypes.batch,
                //       permission: null,
                //       callback: () => {
                //         this.linkToDelete()
                //       },
                //     },
                //     {
                //       label: '批量提交',
                //       id: 'msubmit',
                //       permission: null, // 纯前端操作，不需要权限控制
                //       callback: () => {
                //         this.allsubmit()
                //       },
                //     },
                //     {
                //       label: '复制其他项目底稿',
                //       id: 'copyotherpaper',
                //       permission: null, // 纯前端操作，不需要权限控制
                //       callback: () => {
                //         if (this.catalogId != null) {
                //           this.modalPapervisible = true
                //         } else {
                //           Modal.confirm({
                //             title: '请先选择分类',
                //             content: '请先选择分类。',
                //             okText: '确定',
                //             cancelText: '取消',
                //             okType: 'danger',
                //           })
                //         }
                //       },
                //     },
                //     {
                //       label: '变更分类',
                //       id: 'auditMattersCatalog',
                //       permission: null,
                //       callback: () => {
                //         this.openbgfl()
                //         // const url = '/sd-frame/audit-matters-catalog' // 新页面要打开的路由地址
                //         // openAsTrustId(url, null)
                //       },
                //     },
                //   ]
                // }
              }
            }
          })

          // if (['05', '06', '07'].includes(itemStatus)) {
          //   this.actions = [
          //     {
          //       label: '导出',
          //       id: 'exportItem',
          //       permission: null, // 纯前端操作，不需要权限控制
          //       callback: () => {
          //         this.exportPaperExcel()
          //       },
          //     },
          //     {
          //       label: '导出word',
          //       id: 'exportwordItem',
          //       permission: null, // 纯前端操作，不需要权限控制
          //       callback: () => {
          //         const selectedRowKeys = this.$refs.auditOperatePaperTable.getSelectedRowKeys()
          //         if (selectedRowKeys.length === 0) {
          //           Modal.warning({
          //             title: '提示',
          //             content: '请选择需要导出的工作底稿!',
          //           })
          //         }
          //         if (selectedRowKeys.length > 1) {
          //           Modal.warning({
          //             title: '提示',
          //             content: '一次只能选择一个工作底稿!',
          //           })
          //         }
          //         if (selectedRowKeys.length === 1) {
          //           axios({
          //             url:
          //               'api/xcoa-mobile/v1/iamworkpaperprograme/paperWord/61/' +
          //               selectedRowKeys[0],
          //             method: 'get',
          //             responseType: 'blob',
          //           }).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))
          //             }
          //           })
          //         }
          //       },
          //     },
          //   ]
          //   this.editflag = false
          // }
        }
      })
    },
    changery(values) {
      this.createName = ''
      values.forEach((element) => {
        this.createName = element.name
      })
    },
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-work-paper/flowState',
        method: 'get',
      }).then((res) => {
        const options = []
        res.data.forEach((item, index) => {
          options.push({
            id: index,
            name: item,
          })
        })
        this.flowStateOptions = options
      })
    },
    openbgfl() {
      this.treeselectId = ''
      const selectedRowKeys = this.$refs.auditOperatePaperTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择需要变更分类的工作底稿!',
        })
        return false
      } else {
        this.modalchangeselectId = selectedRowKeys
        this.modalPapertreevisible = true
      }
    },
    handletreeCancel() {
      this.modalPapertreevisible = false
    },
    handletreeOk(e) {
      if (this.treeselectId === '') {
        Modal.warning({
          title: '提示',
          content: '请选择分类!',
        })
        return false
      } else {
        const key = this.modalchangeselectId
        const params = {}
        key.forEach((i) => {
          params[i.toString()] = this.treeselectId.toString()
        })
        AuditOperatePaperService.fnChangeCate(params).then((res) => {
          if (res.data) {
            this.refresh()
          } else {
            Modal.warning({
              title: '提示',
              content: '变更分类失败，请联系管理员!',
            })
          }
        })
      }
      this.modalPapertreevisible = false
    },
    modaltreeSelect(selectkey, info) {
      // 如果点击的是根节点
      this.treeselectId = ''
      if (!info.node.dataRef.props.isroot) {
        this.treeselectId = info.node.dataRef.props.id
      }
    },
    treeSelectframe(selectkey, info) {
      // 如果点击的是根节点
      const expressionsValue = []
      if (selectkey.length > 0) {
        this.catalogId = info.node.dataRef.id
        this.frameexpressions = {
          dataType: 'int',
          name: 'frameClassId',
          op: 'eq',
          intValue: Number(this.catalogId),
        }
        this.expressions = []
        expressionsValue.push(this.projectexpressions)
        if (!info.node.dataRef.props.isroot) {
          expressionsValue.push(this.frameexpressions)
        }
        this.expressions.push({
          dataType: 'exps',
          op: 'and',
          expressionsValue: expressionsValue,
        })
        setTimeout(() => this.refresh(), 100)
      } else {
        this.catalogId = null
        this.expressions = []
        this.expressions.push(this.projectexpressions)
        this.frameexpressions = {
          dataType: 'int',
          name: 'frameClassId',
          op: 'eq',
          intValue: -1,
        }
      }
    },
    // 初始化树信息时默认展示审计框架信息
    treeinit(initinfo) {
      this.recordId = initinfo.key + ''
      // 存储下来
      this.initinfo = initinfo
    },
    // 新建审计框架
    createframe() {
      this.recordId = null
      this.formreadonly = false
      this.formkey++
    },
    // 审计框架下拉框变化事件
    changeframe(value, option) {
      this.frameName = value.label
      this.treekey++
    },
    // 选择上级分类后给对应的域赋值
    fnTreePicker(value) {
      if (value.length > 0) {
        this.$refs.dataTable.getDetailModal().setFieldValue('catalogId', value[0].id)
        this.$refs.dataTable.getDetailModal().setFieldValue('catalogName', value[0].name)
      } else {
        this.$refs.dataTable.getDetailModal().setFieldValue('catalogId', '')
        this.$refs.dataTable.getDetailModal().setFieldValue('catalogName', '')
      }
    },

    // 新建、详情打开新页面
    rowClick(record) {
      const curuser = getUserInfo().account
      let url = '/iam-operate-paper-form?record=' + record.id // 新页面要打开的路由地址
      if (this.editflag) {
        if ((record.flowState === '起草') | (record.flowState === '开始')) {
          // 判断是否当前人
          if (record.nowUserAccount === curuser) {
            url = '/sd-webflow/pages/draft/' + record.instId
          } else {
            url = '/sd-webflow/done-pages/' + record.instId
          }
        } else {
          url = '/sd-webflow/done-pages/' + record.instId
        }
      } else {
        url = '/sd-webflow/done-pages/' + record.instId
      }
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    // 部门下拉框选择事件
    depChanged(value, info) {},
    // 新建保存回调刷新树
    onRecordSaved() {
      this.key = this.key + 1
    },
    // 删除回调
    onRecordsDeleted() {
      this.key = this.key + 1
    },
    deleteRows() {
      const ids = this.$refs.auditMattersTable.getSelectedRowKeys()
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {},
          onCancel: () => {
            resolve()
          },
        })
      })
    },

    createOperatePaper() {
      if (this.catalogId != null) {
        const url =
          '/sd-flow-guide?code=PRODUCT_IAM_GZDG&catalogId=' +
          this.catalogId +
          '&projectId=' +
          this.projectId
        // window.open(url)
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            this.refresh()
          }
        })
      } else {
        Modal.confirm({
          title: '请先选择分类',
          content: '请先选择分类。',
          okText: '确定',
          cancelText: '取消',
          okType: 'danger',
        })
      }
    },
    refresh() {
      this.$refs.auditOperatePaperTable.refresh()
    },
    restartPaper(id) {
      const params = [id]
      AuditOperatePaperService.fnRestart(params).then((res) => {
        if (res.data[0] !== undefined) {
          Modal.warning({
            title: '提示',
            content: res.data[0],
          })
        } else {
          this.refresh()
        }
      })
    },
    // 变更编辑人保存
    change(val) {
      let codes = ''
      let names = ''
      if (val.length > 0) {
        val.forEach((e) => {
          codes += e.code + ','
          names += e.name + ','
        })
        codes = codes.substr(0, codes.length - 1)
        names = names.substr(0, names.length - 1)
      }
      const params = { id: this.changeeditorprojectId, account: codes }
      return new Promise((resolve) => {
        // 分配项目组长配置
        AuditOperatePaperService.fnChangeeditor(params).then((res) => {
          if (res.data) {
            this.$refs.auditOperatePaperTable.clearSelection()
            this.$refs.auditOperatePaperTable.refresh()
          }
        })
      })
    },
    changeeditor(record) {
      this.setType = 'groupLeader'
      const jsonArry = []
      if (record.creatorAccount !== '' && record.creatorAccount !== null) {
        if (record.creatorAccount.indexOf(',') > -1) {
          const codes = record.creatorAccount.split(',')
          const names = record.creatorName.split(',')
          for (let i = 0; i < codes.length; i++) {
            jsonArry.push({ type: 'User', code: codes[i], name: names[i], attrs: [] })
          }
        } else {
          jsonArry.push({
            type: 'User',
            code: record.creatorAccount,
            name: record.creatorName,
            attrs: [],
          })
        }
      }
      this.mainSendUnit = jsonArry
      this.changeeditorprojectId = record.id
      setTimeout(() => {
        this.$refs.assignTeamLeader.openPicker()
      }, 0)
    },
    optbuttonClick(val, record) {
      // 启动项目
      if (val === 'restart') {
        this.restartPaper(record.id)
      } else {
        this.changeeditor(record)
      }
    },
    changemodalPapervisible() {
      this.modalPapervisible = false
    },
    allsubmit() {
      this.treeselectId = ''
      const selectedRowKeys = this.$refs.auditOperatePaperTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择需要批量提交的工作底稿!',
        })
        return false
      } else {
        const rows = this.$refs.auditOperatePaperTable.getSelectedRows()
        let flag = false
        rows.forEach((item) => {
          if (item.flowState !== '起草') {
            flag = true
          }
        })
        if (flag) {
          Modal.warning({
            title: '提示',
            content: '选择的工作底稿尚未处于起草阶段，无法批量提交，请重新提交!',
          })
          return false
        } else {
          this.pending = []
          this.batchSubmitSucceed = []
          this.batchsubmitFailed = []
          selectedRowKeys.forEach((record) => {
            this.pending.push(record)
          })
          AuditOperatePaperService.fnPlSubmit(selectedRowKeys).then((res) => {
            if (res.data) {
              res.data.forEach((item) => {
                const id = item.id
                if (item.code === '-1') {
                  this.batchsubmitFailed.push({ id: id, message: item.message })
                } else {
                  this.batchSubmitSucceed.push(id)
                }
                const index = this.pending.findIndex((item) => item === id)
                this.pending.splice(index, 1)
              })
              this.$refs.auditOperatePaperTable.clearSelection()
              setTimeout(() => {
                this.$refs.auditOperatePaperTable.refresh()
              }, 1500)
            }
          })
        }
      }
    },
    // 高级搜索
    seniorSearch() {
      this.expand = !this.expand
    },
    searchedClick() {
      this.expand = !this.expand
    },
    // 查询
    handleSearch() {
      // 默认查询条件
      const expressionsValue = []
      this.expressions = []
      if (this.frameexpressions.name === undefined) {
        this.expressions.push(this.projectexpressions)
        // this.expressions = [
        //   {
        //     dataType: 'long',
        //     name: 'projectId',
        //     op: 'eq',
        //     longValue: this.$root.$route.query.projectId,
        //   },
        // ]
      } else {
        expressionsValue.push(this.projectexpressions)
        expressionsValue.push(this.frameexpressions)
        this.expressions.push({
          dataType: 'exps',
          op: 'and',
          expressionsValue: expressionsValue,
        })
      }

      // 名称
      if (this.formData.paperTitle) {
        this.expressions.push({
          dataType: 'str',
          name: 'paperTitle',
          op: 'like',
          stringValue: `%${this.formData.paperTitle}%`,
        })
      }
      // 资料编号
      if (this.formData.flowState.length > 0 && typeof this.formData.flowState[0] !== 'string') {
        this.expressions.push({
          dataType: 'str',
          name: 'flowState',
          op: 'like',
          stringValue: `%${this.formData.flowState[0].name}%`,
        })
      }
      if (this.formData.creatorName) {
        this.expressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.createName}%`,
        })
      }
      console.log(this.expressions)
    },

    addExpression() {
      const projectId = this.$root.$route.query.projectId
      this.expressions.push({
        dataType: 'long',
        name: 'projectId',
        op: 'eq',
        longValue: projectId,
      })
      AuditProjectuserService.isProjectLeader(projectId, 'all').then((res) => {
        if (res && res.data === false) {
          this.expressions.push({
            dataType: 'str',
            name: 'flowState',
            op: 'like',
            stringValue: `%结束%`,
          })
        }
      })
    },
    // 标题格式化
    formatterTitle(val, length) {
      var resultArry = []
      let title = ''
      let result = ''
      if (val === undefined || val === '' || val === '[]') {
        resultArry.push(title)
        resultArry.push(result)
        return resultArry
      } else {
        try {
          JSON.parse(val).forEach((e) => {
            result += e.name + ','
          })
        } catch (e) {
          result = val
        }
        if (result.lastIndexOf(',') > 0) {
          result = result.substr(0, result.length - 1)
        }
        title = result
        if (result.length > length) {
          result = result.substr(0, length) + '...'
        }
        resultArry.push(title)
        resultArry.push(result)
        return resultArry
      }
    },
    // 重置年份
    resetForm() {
      this.formData.flowState = ''
      this.formData.creatorName = ''
    },
    linkToDelete() {
      const selectedRowKeys = this.$refs.auditOperatePaperTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的数据！',
        })
        return
      }
      const curuser = getUserInfo().account
      let flag = false
      if (
        this.role.findIndex((i) => i === '01') > -1 ||
        this.role.findIndex((i) => i === '05') > -1
      ) {
        flag = true
      }
      if (!flag) {
        // 不是组长和副组长的，只能删自己的 ==也不能删审计事项分配过来的==
        const selectedRow = this.$refs.auditOperatePaperTable.getSelectedRows()
        selectedRow.forEach((item, index) => {
          if (item.creatorAccount !== curuser) {
            const si = selectedRowKeys.findIndex((i) => i === item.id)
            if (si !== -1) {
              selectedRowKeys.splice(si, 1)
              this.batchsubmitFailed.push({ id: item.id, message: '不允许删除非本人工作底稿' })
            }
          }
          if (item.itemId) {
            const si = selectedRowKeys.findIndex((i) => i === item.id)
            if (si !== -1) {
              selectedRowKeys.splice(si, 1)
              this.batchsubmitFailed.push({ id: item.id, message: '不允许删除分配的审计事项' })
            }
          }
        })
      }
      if (selectedRowKeys.length === 0) {
        this.$refs.auditOperatePaperTable.clearSelection()
        this.$refs.auditOperatePaperTable.refresh()
      } else {
        return new Promise((resolve) => {
          let flag = true
          const rows = this.$refs.auditOperatePaperTable.getSelectedRows()
          rows.forEach((r) => {
            if (r.endType) {
              if (r.endType !== 0) {
                flag = false
              }
            }
          })
          if (!flag) {
            Modal.error({
              title: '删除失败：存在不是起草状态的数据',
            })
            resolve()
          } else {
            Modal.confirm({
              title: '您确定删除这项内容吗？',
              content: '删除这条数据后，就无法恢复初始的状态。',
              okText: '删除',
              okType: 'danger',
              onOk: () => {
                axios({
                  url: 'api/xcoa-mobile/v1/page/iamWorkPaper',
                  method: 'delete',
                  params: {
                    ids: selectedRowKeys.join(','),
                  },
                })
                  .then(() => {
                    const msg = '删除成功'
                    message.success(msg)
                    this.$refs.auditOperatePaperTable.clearSelection()
                    this.$refs.auditOperatePaperTable.refresh()
                  })
                  .catch((err) => {
                    const msg = errorUtil.getMessage(err) || '删除失败'
                    message.error(msg)
                  })
                  .finally(resolve)
              },
              onCancel: () => {
                resolve()
              },
            })
          }
        })
      }
    },
    exportPaperExcel() {
      let idArr = this.$refs.auditOperatePaperTable.getSelectedRowKeys()

      if (idArr === undefined || idArr.length === 0) {
        idArr = this.exportIds
      }

      const conditions = { configId: '111', ids: idArr }

      axios({
        url: 'api/xcoa-mobile/v1/iamworkpapermaterial/exportPaper',
        method: 'post',
        data: conditions,
        responseType: 'blob',
      }).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))
        }
      })
    },
    tableDataLoaded(data) {
      data.respData.data.forEach((item) => {
        this.exportIds.push(item.id)
      })
    },
    after() {
      this.refresh()
    },
  },
}
</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%;
    }
  }
  .success {
    color: $alert-success-icon-color;
  }

  .error {
    color: $alert-error-icon-color;
  }

  :global(.part-time) {
    padding-right: 5px !important;
  }
}

.operatecol {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  float: left;
  :global(.ant-btn-sm) {
    padding: 0 3px;
  }
}
.operatemodalpaper :global(.treewrap_iam-audit-frame-tree_product) {
  width: 100%;
}
:global(.frame-div) {
  width: 180px;
}
</style>
