<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <div :class="$style.rightcard">
        <a-card>
          <div :class="$style.wrapper">
            <audit-advanced-query
              :expand="expand"
              :search-data="formData"
              :ref-name="'searchform'"
              :search-style="{
                height: '130px',
                left: '20px',
                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="docTitle">
                    <a-input v-model="formData.docTitle" allow-clear />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item :label="'编制人员'" prop="authName">
                    <a-input v-model="formData.authName" allow-clear />
                  </a-form-model-item>
                </a-col>
              </template>
            </audit-advanced-query>
            <SdDataTableEx
              ref="oaTable"
              :form-id="formId"
              :columns="columns"
              :actions="actions"
              :filter-expressions="expressions"
              :show-selection="true"
              :show-advance-query="true"
              :search-fields="['docTitle']"
              :row-selection="{ type: 'radio' }"
              @recordsDeleted="onRecordsDeleted"
              @searchbtnClick="searchbtnClick"
            >
              <a
                slot="fldSubject"
                slot-scope="text, record"
                :title="text"
                @click="fnReadDoc(record)"
                >{{ text }}</a
              >

              <a slot="opt" slot-scope="text, record" @click="fnEditDoc(record)">编辑</a>
            </SdDataTableEx>
          </div>
        </a-card>
      </div>
    </div>
  </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 TableColumnTypes from '@/common/services/table-column-types'
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import AuditProjectuserService from '@product/iam/audit/work/projectuser/audit-projectuser-service'
import auditAdvancedQueryMixins from '../../../components/audit-advanced-query-mixins'
import auditAdvancedQuery from '../../../components/audit-advanced-query.vue'
import components from './_import-components/iam-audit-leavemeeting-import'

export default {
  name: 'IamAuditLeavemeeting',
  metaInfo: {
    title: '离场会',
  },
  components: {
    auditAdvancedQuery,
    SdDataTableEx,
    ...components,
  },
  mixins: [auditAdvancedQueryMixins],
  props: {
    // 是不是用于选择数据
    isSelectd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formData: {
        orgName: '',
        orgId: '',
        cUser: '',
      },
      expand: false,
      categorys: [],
      activeKey: 'textlist',
      isKmAdmin: false,
      expressions: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '文件标题',
          dataIndex: 'docTitle',
          scopedSlots: { customRender: 'fldSubject' },
          width: '40%',
        },
        {
          title: '被审计单位',
          dataIndex: 'auditUnitName',
          width: '20%',
        },
        {
          title: '编制人员',
          dataIndex: 'authName',
        },
        {
          title: '编制日期',
          dataIndex: 'authTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
        },
        {
          title: '文档状态',
          dataIndex: 'reservestring1',
          sorter: true,
        },
        {
          dataIndex: 'creatorAccount',
          sdHidden: true,
        },
      ],
      // actions: [
      //   {
      //     label: '删除',
      //     permission: null, // 纯前端操作，不需要权限控制
      //     id: 'delete',
      //     callback: this.deleteRows,
      //     type: TableActionTypes.batch,
      //   },
      //   {
      //     label: '新建',
      //     permission: null, // 纯前端操作，不需要权限控制
      //     id: 'create', // 没写type，一般按钮
      //     callback: () => {
      //       this.fnCreatDoc()
      //     },
      //     type: TableActionTypes.primary,
      //   },
      // ],
      actions: [],
      businessTypeId: null,
      typeId: null,
      typeName: '',

      formId: 'iamLeaveMeeting',
      // 图文列表参数
      showCreateBtn: false,
      showDeleteBtn: false,
      pictureData: [],
      pagination: {
        onChange: (page) => {
          this.paginationChange(page)
        },
        current: 1,
        pageSize: 8,
        showTotal(total) {
          return `共${total}条`
        },
      },
      loading: false, // 图文列表数据的loading
      orderType: 'creationTime',
      creationTimeDesc: true,
      pictureRowSelection: [],
      searchText: '',
      picList: '',
      projectId: this.$root.$route.query.projectId,
    }
  },
  // 图文列表参数变化更新数据
  watch: {
    orderType() {
      this.pictureListRefresh()
    },
    creationTimeDesc() {
      this.pictureListRefresh()
    },
  },
  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
    },

    // 离场会按钮展示条件梳理：1、新建、删除按钮对所有角色展示
    // 2、结束环节之后按钮不展示
    // 3、只是阅读人员不展示按钮
    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 = []
          } else {
            //   this.actions = [
            //     {
            //       label: '删除',
            //       permission: null, // 纯前端操作，不需要权限控制
            //       id: 'delete',
            //       callback: this.deleteRows,
            //       type: TableActionTypes.batch,
            //     },
            //     {
            //       label: '新建',
            //       permission: null, // 纯前端操作，不需要权限控制
            //       id: 'create', // 没写type，一般按钮
            //       callback: () => {
            //         this.fnCreatDoc()
            //       },
            //       type: TableActionTypes.primary,
            //     },
            //   ]
            // }
            if (
              readAuthorityCodes != null &&
              readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
              !isProjectUser
            ) {
              this.actions = []
            } else {
              this.actions = [
                {
                  label: '删除',
                  permission: null, // 纯前端操作，不需要权限控制
                  id: 'delete',
                  callback: this.deleteRows,
                  type: TableActionTypes.batch,
                },
                {
                  label: '新建',
                  permission: null, // 纯前端操作，不需要权限控制
                  id: 'create', // 没写type，一般按钮
                  callback: () => {
                    this.fnCreatDoc()
                  },
                  type: TableActionTypes.primary,
                },
              ]

              // 判断权限
              // axios({
              //   url: 'api/xcoa-mobile/v1/iamprojectuser/userProject?projectId=' + projectId,
              //   method: 'get',
              // }).then((res) => {
              //   const datas = res.data
              //   if (!datas.includes('02') && !datas.includes('05')) {
              //     // 项目组员没有删除权限
              //     this.actions = [
              //       {
              //         label: '新建',
              //         permission: null, // 纯前端操作，不需要权限控制
              //         id: 'create', // 没写type，一般按钮
              //         callback: () => {
              //           this.fnCreatDoc()
              //         },
              //         type: TableActionTypes.primary,
              //       },
              //     ]
              //   } else {
              //     this.actions = [
              //       {
              //         label: '删除',
              //         permission: null, // 纯前端操作，不需要权限控制
              //         id: 'delete',
              //         callback: this.deleteRows,
              //         type: TableActionTypes.batch,
              //       },
              //       {
              //         label: '新建',
              //         permission: null, // 纯前端操作，不需要权限控制
              //         id: 'create', // 没写type，一般按钮
              //         callback: () => {
              //           this.fnCreatDoc()
              //         },
              //         type: TableActionTypes.primary,
              //       },
              //     ]
              //   }
              // })
            }
          }
        }
      })
    },
    searchedClick() {
      this.expand = false
    },
    // 查询
    handleSearch() {
      this.expressions = []

      this.addExpression()

      // 文件标题
      if (this.formData.docTitle) {
        this.expressions.push({
          dataType: 'str',
          name: 'docTitle',
          op: 'like',
          stringValue: `%${this.formData.docTitle}%`,
        })
      }

      // 编制人员
      if (this.formData.authName) {
        this.expressions.push({
          dataType: 'str',
          name: 'authName',
          op: 'like',
          stringValue: `%${this.formData.authName}%`,
        })
      }
    },
    // 新建
    fnCreatDoc() {
      var url = '/iam-audit-leavemeeting-form?projectId=' + this.projectId
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          return this.$refs.oaTable.refresh(true)
        }
      })
    },
    fnEditDoc(record) {
      setTimeout(() => {
        this.$refs.oaTable.refresh()
        this.loadData()
      }, 5000)

      var url = `/km-knowledage-form?&typeId=${this.typeId}&typeName=${this.typeName}&record=${record.id}`

      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          return this.$refs.oaTable.refresh(true)
        }
      })
    },
    // 查看
    fnReadDoc(record) {
      setTimeout(() => {
        this.$refs.oaTable.refresh()
        this.loadData()
      }, 5000)

      // 当前用户
      var currentUser = getUserInfo().name
      var mode = null
      var type = 0

      if (record.authName === currentUser) {
        mode = 'EDIT'
        if (record.reservestring1 === '已结束') {
          type = 1
        } else {
          type = 2
        }
      } else {
        mode = 'VIEW'
      }

      window.open(
        `#/iam-audit-leavemeeting-form?record=${record.id}&type=${type}&mode=${mode}&projectId=${this.projectId}`,
        '_blank'
      )
    },
    // 图片列表页面翻页
    paginationChange(page) {
      this.pagination.current = page
      this.loadData()
    },
    pictureListRefresh(toFirstPage) {
      if (toFirstPage) this.pagination.current = 1
      if (!this.isSelectd) {
        return this.loadData()
      }
    },
    // 列表删除数据时刷新一下
    onRecordsDeleted() {
      this.$refs.tree.refresh() // 刷新树
    },
    // 列表删除数据
    deleteRows() {
      const selectedRowKeys = this.$refs.oaTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      // 当前用户
      var currentUser = getUserInfo().account
      var rows = this.$refs.oaTable.getSelectedRows()
      var titles = []
      for (var i = 0; i < rows.length; i++) {
        if (currentUser !== rows[i].creatorAccount) {
          titles.push(rows[i].docTitle)
        }
      }
      // 判断是否选择了非自己的离场会
      if (titles.length > 0) {
        // 判断是否项目组长/项目副组长
        AuditProjectuserService.isProjectLeader(parseInt(this.projectId), 'head').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, this.formId).then((res) => {
            if (res.status === 200) {
              Message.success({ content: '删除成功！' }, 1).then(() => {
                this.$refs.oaTable.clearSelection()
                this.$refs.oaTable.refresh()
                this.loading = false
              })
            }
          })
        },
      })
    },
    // 项目负责人,项目组长/项目副组长【查看】所有《离场会》;项目主审/项目组员【查看】所有“已结束”《离场会》
    addExpression() {
      this.expressions.push({
        dataType: 'long',
        name: 'projectId',
        op: 'eq',
        longValue: parseInt(this.projectId),
      })
      AuditProjectuserService.isProjectLeader(parseInt(this.projectId), 'all').then((res) => {
        if (res && res.data === false) {
          this.expressions.push({
            dataType: 'exps',
            op: 'or',
            expressionsValue: [
              {
                dataType: 'str',
                name: 'creatorAccount',
                op: 'eq',
                stringValue: getUserInfo().account,
              },
              {
                dataType: 'str',
                name: 'reservestring1',
                op: 'like',
                stringValue: `%已结束%`,
              },
            ],
          })
        }
      })
    },
  },
}
</script>

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