<template>
  <div>
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{
          height: '130px',
          left: '0px',
          top: '45px !important',
          width: 'calc(100% - 5px) !important',
          margin: 'auto',
        }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item label="文件标题" prop="fieldName">
              <a-input v-model="formData.fieldName" 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 />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table-ex
        ref="iamAuditIntoMettingTable"
        form-id="iamAuditIntoMetting"
        page-id="work/intoMeeting/iamAuditIntoMetting"
        :filter-expressions="expressions"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :search-fields="['fieldName']"
        :custom-delete-fun="deleteRows"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a :title="text" @click="rowClick(record)">{{ text }}</a>
        </div>
      </sd-data-table-ex>
    </a-card>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import { Modal, Message } from 'ant-design-vue'
import PageService from '@/common/services/page-service'
import { getUserInfo } from '@/common/store-mixin'
import TableActionTypes from '@/common/services/table-action-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import AuditProjectuserService from '@product/iam/audit/work/projectuser/audit-projectuser-service'
import TableColumnTypes from '@/common/services/table-column-types'
import auditAdvancedQuery from '../../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../../components/audit-advanced-query-mixins'
import components from './_import-components/iam-audit-into-meeting-import'

export default {
  name: 'IamAuditIntoMeeting',
  metaInfo: {
    title: '进场会',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      searchform: 'searchform',
      formData: {
        fieldName: '',
        creatorName: '',
      },
      projectId: this.$root.$route.query.projectId,
      expressions: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '文件标题',
          dataIndex: 'fieldName',
          scopedSlots: { customRender: 'islink' },
          width: '40%',
        },
        {
          title: '被审计单位',
          dataIndex: 'auditedUnit',
          width: '20%',
        },

        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
        },
        {
          title: '文档状态',
          dataIndex: 'endType',
          sorter: true,
        },
        {
          dataIndex: 'creatorAccount',
          sdHidden: true,
        },
      ],
      actions: [],
      // actions: [
      //   {
      //     label: '新建',
      //     id: 'new',
      //     permission: null,
      //     type: TableActionTypes.primary,
      //     callback: () => {
      //       const url = '/iam-audit-into-meeting-form?projectId=' + this.projectId // 新页面要打开的路由地址
      //       crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
      //         if (refreshFlag) {
      //           // 这里写或者调刷新的方法
      //           this.refresh()
      //         }
      //       })
      //     },
      //   },
      //   {
      //     label: '删除',
      //     id: 'delete',
      //     permission: null,
      //     type: TableActionTypes.oa.delete,
      //   },
      // ],
      mode: 'EDIT',
    }
  },
  created() {
    this.addExpression()
  },
  mounted() {
    this.isShowBtn()
  },
  methods: {
    // 查看当前登录人是否项目成员，如果同时是项目阅读人员，取最大权限（项目成员权限）
    inProjectUser(userList) {
      var isProjectUser = false
      userList.map((item) => {
        if (item.userAccount === getUserInfo().account) {
          isProjectUser = true
          return isProjectUser
        }
      })
      return isProjectUser
    },
    // 是否显示按钮 禅道bug21826需要，关闭项目后各阶段都不能再新建（包括其他操作按钮）
    isShowBtn() {
      const projectId = this.$root.$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)
          if (['05', '06', '07'].includes(itemStatus)) {
            this.actions = []
            this.mode = 'VIEW'
          } else {
            if (
              readAuthorityCodes != null &&
              readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
              !isProjectUser
            ) {
              this.actions = []
            } else {
              this.actions = [
                {
                  label: '新建',
                  id: 'new',
                  permission: null,
                  type: TableActionTypes.primary,
                  callback: () => {
                    const url = '/iam-audit-into-meeting-form?projectId=' + this.projectId // 新页面要打开的路由地址
                    crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
                      if (refreshFlag) {
                        // 这里写或者调刷新的方法
                        this.refresh()
                      }
                    })
                  },
                },
                {
                  label: '删除',
                  id: 'delete',
                  permission: null,
                  type: TableActionTypes.oa.delete,
                },
              ]
            }
          }
          // if (['05', '06', '07'].includes(itemStatus)) {
          //   this.actions = []
          //   this.mode = 'VIEW'
          // } else {
          //   this.actions = [
          //     {
          //       label: '新建',
          //       id: 'new',
          //       permission: null,
          //       type: TableActionTypes.primary,
          //       callback: () => {
          //         const url = '/iam-audit-into-meeting-form?projectId=' + this.projectId // 新页面要打开的路由地址
          //         crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          //           if (refreshFlag) {
          //             // 这里写或者调刷新的方法
          //             this.refresh()
          //           }
          //         })
          //       },
          //     },
          //     {
          //       label: '删除',
          //       id: 'delete',
          //       permission: null,
          //       type: TableActionTypes.oa.delete,
          //     },
          //   ]
          // }
        }
      })
    },
    // 新建、详情打开新页面
    rowClick(record) {
      // 查看或编辑
      var currentUser = getUserInfo().account
      if (currentUser === record.creatorAccount) {
        // 编辑
        //  mode = 'EDIT'
      } else {
        // 查看
        this.mode = 'VIEW'
      }
      const url =
        '/iam-audit-into-meeting-form?record=' +
        record.id +
        '&projectId=' +
        this.projectId +
        '&mode=' +
        this.mode // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    // 刷新列表
    refresh() {
      this.$refs.iamAuditIntoMettingTable.refresh()
    },
    handleSearch() {
      this.expressions = []
      this.addExpression()
      // 名称
      if (this.formData.fieldName) {
        this.expressions.push({
          dataType: 'str',
          name: 'fieldName',
          op: 'like',
          stringValue: '%' + this.formData.fieldName + '%',
        })
      }
      // 人员
      if (this.formData.creatorName) {
        this.expressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: '%' + this.formData.creatorName + '%',
        })
      }
    },
    // 列表删除数据
    deleteRows() {
      const selectedRowKeys = this.$refs.iamAuditIntoMettingTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      // 当前用户
      var currentUser = getUserInfo().account
      var rows = this.$refs.iamAuditIntoMettingTable.getSelectedRows()
      var titles = []
      for (var i = 0; i < rows.length; i++) {
        if (currentUser !== rows[i].creatorAccount) {
          titles.push(rows[i].fieldName)
        }
      }
      // 判断是否选择了非自己的进场会
      console.log(titles.length)
      if (titles.length > 0) {
        // 判断是否项目组长/项目副组长
        AuditProjectuserService.isProjectLeader(parseInt(this.projectId), 'intoMeetingZ').then(
          (res) => {
            if (res && res.data === true) {
              this.doDelete(selectedRowKeys)
            } else {
              Modal.info({
                content: (h) => {
                  const info = [h('p', null, '请选择自己的进场会，以下非您创建：')]
                  titles.forEach((t) => {
                    info.push(t)
                    info.push(h('br'))
                  })
                  return h('p', info)
                },
              })
            }
          }
        )
      } else {
        this.doDelete(selectedRowKeys)
      }
    },
    doDelete(selectedRowKeys) {
      Modal.confirm({
        title: '你确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          this.loading = true
          const params = {
            ids: selectedRowKeys.join(','),
          }
          PageService.delete(params, 'iamAuditIntoMetting').then((res) => {
            if (res.status === 200) {
              Message.success({ content: '删除成功！' }, 1).then(() => {
                this.$refs.iamAuditIntoMettingTable.clearSelection()
                this.$refs.iamAuditIntoMettingTable.refresh()
              })
            }
          })
        },
      })
    },
    // 项目主审/项目组员 【查看】所有“已结束”《进场会》
    addExpression() {
      this.expressions.push({
        dataType: 'long',
        name: 'projectId',
        op: 'eq',
        longValue: parseInt(this.projectId),
      })

      AuditProjectuserService.isProjectLeader(parseInt(this.projectId), 'intoMeetingZZ').then(
        (res) => {
          // 查看自己的或者 已结束的

          if (res && res.data === true) {
            this.expressions.push({
              dataType: 'exps',
              op: 'or',
              expressionsValue: [
                {
                  dataType: 'str',
                  name: 'creatorAccount',
                  op: 'eq',
                  stringValue: getUserInfo().account,
                },
                {
                  dataType: 'long',
                  name: 'endType',
                  op: 'eq',
                  longValue: 1,
                },
              ],
            })
          }
        }
      )
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
