<template>
  <sd-detail-form
    v-show="initialled"
    ref="docform"
    :page-id="this.$route.query.pageId"
    :record-id="this.$route.query.projectId ? this.$route.query.projectId : null"
    :class="$style.form"
    :read-only="!isLeader"
    :portal-prefix="isLeader ? null : 'false'"
    @close="close(true)"
    @saved="saved"
    @actionBtnClick="actionBtnClick"
  >
    <template v-slot="{ formData, model, fields }">
      <table>
        <tr>
          <td style="border: none">
            <audit-advanced-group
              :expand="expand"
              expand-str="expand"
              group-label="人员信息"
              @changedClick="changedClick"
            ></audit-advanced-group>
          </td>
        </tr>
      </table>

      <table v-show="expand">
        <tr>
          <td colspan="4" :class="$style.subTable">
            <sd-form-by-builder
              v-if="initialled"
              class="user-table"
              :form-data="formData.pageFormData"
            ></sd-form-by-builder>
          </td>
        </tr>
      </table>
    </template>
  </sd-detail-form>
</template>

<script>
import { message } from '@/common/one-ui'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import auditCpmProjectUserService from './audit-cpm-project-user-service'
import components from './_import-components/audit-cpm-project-user-import'

export default {
  name: 'AuditCpmProjectUser',
  metaInfo: {
    title: '项目成员',
  },
  components: {
    auditAdvancedGroup,
    ...components,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      expand: true,
      initialled: false,
      key: 0,
      projectId: undefined,
      isLeader: false,
    }
  },
  mounted() {
    const ini = setInterval(() => {
      if (this.$refs.docform) {
        try {
          this.filter(this.$refs.docform.formData.pageFormData)
          // 获取项目ID
          this.projectId = this.$route.query.projectId
          if (this.$route.query.groupId.toString() !== '1') {
            this.projectId = this.$route.query.groupId
          }
          // 获取组员信息
          this.getProjectUser()
          // 判断当前登陆人员是否为组长
          this.getProjectUserRole()

          clearInterval(ini)
        } catch {}
      }
    }, 100)
  },
  methods: {
    saved() {
      // 保存成功后
      message.success({ content: '保存成功', key: 'messagekey' })
    },
    close(flag) {
      window.close()
    },
    filter(pageFormData) {
      // 升级新加的参数，使用这个判断是否展示这个字段
      this.$refs.docform.$refs.form.displayExprResults.CPM_PROJECT_MEMBER = 'true'
      const formData = pageFormData
      formData.pageFieldInfos.forEach((item) => {
        if (item.name !== 'CPM_PROJECT_MEMBER') {
          item.attrFD.hidden = true
        } else {
          item.attrFD.hidden = false
          // 系统创建的人员不可删除
          item.attrFD.formItemProps.inputProps.showSelection = (record) => {
            return record.FLAG !== 1
          }
        }
      })
      return formData
    },
    // 判断当前登陆人员是否为组长
    getProjectUserRole() {
      auditCpmProjectUserService.getProjectUserRole(this.projectId).then((res) => {
        this.isLeader = res
      })
    },
    // 获取项目成员信息
    getProjectUser() {
      auditCpmProjectUserService.getProjectUser(this.projectId).then((res) => {
        const userList = res.map((item) => {
          return {
            MEMBER_OPT: JSON.stringify(item.memberOpt),
            MAIN_ID: item.mainId,
            MEMBER_ROLE: item.memberRole,
            id: item.id,
            TASK_DESC: item.taskDesc,
            FLAG: item.flag,
          }
        })
        this.$refs.docform.setFieldValue('CPM_PROJECT_MEMBER', userList)
        this.initialled = true
      })
    },
    actionBtnClick(evt, btn) {
      if (btn.buttonId === 'save') {
        // 停止默认事件，走自己的保存
        evt.preventDefault()
        // 判断表中是否有重复
        let flag = true
        const ulist = this.$refs.docform.getFieldValue('CPM_PROJECT_MEMBER')
        let tsxx = '请完善人员表中的人员和角色信息!'
        // 判断子表是否都已填完
        const btnList = document.querySelectorAll('.operation_sd-child-table_common')
        btnList.forEach((item) => {
          if (item.innerHTML.includes('保存')) {
            flag = false
          }
        })
        if (!flag) {
          message.warning('请保存编辑行，再执行此操作', 1)
          return
        }
        // 因为组长可能存在多人情况，拆分数据
        const userList = []
        const leaderList = []
        ulist.forEach((item) => {
          JSON.parse(item.MEMBER_OPT).forEach((user) => {
            userList.push({
              ID: user.code,
              MEMBER_ROLE: item.MEMBER_ROLE,
            })
            if (item.MEMBER_ROLE.toString() === '1') {
              // 记录组长
              leaderList.push(user)
            }
          })
        })
        // 判断人员是否重复
        userList.forEach((i) => {
          if (userList.filter((u) => u.ID === i.ID).length > 1) {
            flag = false
            tsxx = '人员表中数据重复！'
          }
        })
        // 判断组长角色不可修改
        if (
          ulist.filter((item) => item.FLAG === 1 && item.MEMBER_ROLE.toString() === '1').length ===
          0
        ) {
          flag = false
          tsxx = '系统生成数据不可修改，请修改数据'
        }
        // 不能有两个组长角色
        if (ulist.filter((item) => item.MEMBER_ROLE.toString() === '1').length > 1) {
          flag = false
          tsxx = '组长角色不可新建，请修改数据'
        }
        if (!flag) {
          message.warning(tsxx, 1)
          return
        }
        // 判断组长不可修改
        const groupId = this.$route.query.groupId
        if (groupId.toString() === '1') {
          //  这里是主项目，直接判断主表
          const maniLeader = this.$refs.docform.getFieldValue('SUBMITTER_ACCOUNTS').split(',')
          // 数量是否有变化
          if (maniLeader.length !== leaderList.length) {
            tsxx = '组长角色人员不可修改，请检查数据'
            flag = false
          } else {
            maniLeader.forEach((item) => {
              if (
                leaderList.filter((user) => {
                  return user.code === item
                }).length === 0
              ) {
                tsxx = '组长角色人员不可修改，请检查数据'
                flag = false
              }
            })
          }
        } else {
          // 这是子项目，需要获取分组表里的数据进行判断
          const groupList = this.$refs.docform.getFieldValue('CPM_SUB_PROJECT')
          const groupData = groupList.filter((item) => item.id === groupId)
          const subLeader = JSON.parse(groupData[0].LEADER_OPT)
          // 数量是否有变化
          if (subLeader.length !== leaderList.length) {
            tsxx = '组长角色人员不可修改，请检查数据'
            flag = false
          } else {
            subLeader.forEach((item) => {
              if (
                leaderList.filter((user) => {
                  return user.code === item.code
                }).length === 0
              ) {
                tsxx = '组长角色人员不可修改，请检查数据'
                flag = false
              }
            })
          }
        }
        if (!flag) {
          message.warning(tsxx, 1)
        } else {
          // 进行保存
          const data = ulist.map((item) => {
            return {
              id: item.id && !item.id.includes('fakeId_') ? item.id : null,
              memberOpt: JSON.parse(item.MEMBER_OPT),
              memberRole: item.MEMBER_ROLE,
              taskDesc: item.TASK_DESC,
              memberName: JSON.parse(item.MEMBER_OPT)[0].name,
              memberId: JSON.parse(item.MEMBER_OPT)[0].code,
              memberAccount: JSON.parse(item.MEMBER_OPT)[0].code,
              projectId: null,
              mainId: this.projectId.toString(),
              flag: item.FLAG,
            }
          })
          auditCpmProjectUserService.setProjectUser(this.projectId, data).then((res) => {
            message.success('保存成功', 1)
          })
        }
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.form {
  :global(.ant-form-item-control-wrapper) {
    margin: auto;
    width: 100% !important;
    text-align: center;
  }
  :global(.ant-form-item-control) {
    margin-top: 10px;
  }
  :global(.style-div) {
    display: none;
  }
}
.sub-table {
  table {
    width: 100%;
  }
}
</style>
