<template>
  <div>
    <a-spin :spinning="spinning">
      <sd-detail-form
        ref="form"
        v-sd-watermark="waterMark"
        :page-id="pageId"
        form-id="iamAuditProject"
        :record-id="this.$route.query.projectId ? parseInt(this.$route.query.projectId) : null"
        :class="$style.form"
        @saved="saved"
        @close="close(true)"
        @modifyLogCustomData="modifyLogCustomData"
      >
        <template v-slot="{ model, fields }">
          <table>
            <tr>
              <sd-form-item-td name="iamProjectUserList" :colspan="4" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group :group-label="'人员信息'">
                    <template>
                      <div
                        style="position: relative;z-index: 9;float: right;padding-top: 3px;margin-right: 170px;color: #40a9ff;"
                        ><a-tooltip
                          title="项目成员评价包括审计组评价和公开评价，分别采用10分制，最终加权平均。审计组评价可基于工作能力、工作态度、工作成绩三个方面评价，建议工作能力、工作态度、工作成绩评价打分分别不超过3分、3分、4分。公开评价由审计组全体人员根据审计项目及本人述职汇报情况对审计组成员打分评价。"
                          ><a-icon type="question-circle-o" />评分说明</a-tooltip
                        >
                      </div>
                      <!-- 添加按钮，打开选人组件 -->
                      <a-button
                        v-if="hasLeaderAuthority"
                        type="link"
                        :class="$style.addBtn"
                        @click="openProjectUserSelect"
                      >
                        <a-icon type="plus-circle" :theme="'filled'" />
                        添加
                      </a-button>
                      <iam-audit-user-child-table
                        :key="tablekey"
                        ref="tabaData"
                        v-model="model.iamProjectUserList"
                        :addbuttonvisiable="false"
                        :show-selection="showSelection"
                        :class="$style.deptPlanChild"
                        label=""
                        :fields="
                          Array.from(fields.iamProjectUserList.attr.dync).filter((item) => {
                            return item.name !== 'userAccount'
                          })
                        "
                        :savebuttonvisiable="false"
                        :columns="columns"
                        :dzcl="true"
                        :read-only="!hasLeaderAuthority"
                        :patch-save="true"
                        @change="saveChange"
                        @deleted="deletedFun"
                      >
                        <template v-slot:examineResult="{ field, text, index, value }">
                          <span>{{ text }}</span>
                        </template>
                      </iam-audit-user-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item-td>
            </tr>
          </table>

          <!-- 选人组件 -->
          <div v-show="false">
            <sd-user-picker
              ref="projectUserSelect"
              :single="false"
              :read-only="false"
              @change="projectUserChange"
            />
          </div>
          <div v-if="hasLeaderAuthority" style="margin-top: 20px;text-align: center;border:none">
            <a-button type="primary" @click="saveForm">保存</a-button>
          </div>
          <table>
            <tr>
              <td style="padding-left:5px;border:none">
                <audit-advanced-group
                  :expand="rychange"
                  :expand-str="'rychange'"
                  :group-label="'人员变更记录'"
                  tablestyle="''"
                  @changedClick="changedClick"
                ></audit-advanced-group>
              </td>
            </tr>
          </table>

          <!-- <tr>
          <td :colspan="4">
            <audit-advanced-group :group-label="'人员变更记录'">
              <template> -->
          <table
            v-for="(bg, index) in modifyLogs"
            v-show="rychange"
            :key="index"
            :class="$style.tablexm"
          >
            <tr>
              <td style="width:160px;text-align:right;vertical-align:top">{{ bg.creatorName }} </td>
              <td colspan="3">
                <div
                  style="width: 18px;margin-left:2px;font-size: 8px;color: #fff;text-align:center;background-color: lightgreen;border-radius: 100%;"
                  >√
                </div>
                <div style="padding-left:10px;margin-left:9px;border-left:1px solid gray"
                  >{{ bg.creationTime | sdDateFormat('YYYY-MM-DD HH:mm:ss') }}
                  <table v-for="(val, key, index) in bg.xx" :key="index">
                    <tr>
                      <td :class="$style.changeUser">{{ key }}：</td>
                      <td>
                        <table>
                          <tr v-for="(x, index) in val" :key="index">
                            <td>[{{ x.fieldName === 'userId' ? '人员姓名' : x.fieldDesc }}]</td>
                            <td>
                              <span v-if="x.oldValue !== ''">
                                "{{ getValue(x.oldValue, x.fieldName) }}" 改为 "{{
                                  getValue(x.newValue, x.fieldName)
                                }}"
                              </span>
                              <span v-else style="color:green">
                                {{ getValue(x.newValue, x.fieldName) }}
                              </span>
                            </td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                  </table>
                </div>
              </td>
            </tr>
          </table>

          <!-- <table style="margin-top:50px;width:100%">
            <tr>
              <td>
                <span>
                  <div v-for="action in modifyLogs" :key="action.creationTime + action.creatorName">
                    <div>
                      <sd-user-item
                        :users="[{ code: action.creatorAccount, name: action.creatorName }]"
                      ></sd-user-item>
                      <span>
                        {{ action.creationTime | sdDateFormat('YYYY-MM-DD HH:mm:ss') }}
                      </span>
                      <sd-user-item
                        :users="[
                          { code: action.modifiedUserAccount, name: action.modifiedUserName },
                        ]"
                      ></sd-user-item>
                    </div>
                    <div v-for="item in action.details" :key="item.id" style="padding-left:50px">
                      <template v-if="item.fieldName === 'add' || item.fieldName === 'delete'">
                        {{ item.fieldDesc }}
                      </template>
                      <template v-else>
                        <span>[{{ item.fieldName === 'userId' ? '人员' : item.fieldDesc }}]</span>
                        <template v-if="item.oldValue !== null">
                          <span :class="$style.oldVal"
                            ><template
                              v-if="
                                item.fieldName === 'joinEndTime' ||
                                  item.fieldName === 'joinStartTime'
                              "
                            >
                              {{ parseInt(item.oldValue, 10) | sdDateFormat('YYYY-MM-DD') }}
                            </template>
                            <template v-else-if="item.fieldName === 'userType'">
                              {{ getUserType(item.oldValue) }}
                            </template>
                            <template v-else-if="item.fieldName === 'userId'">
                              <sd-user-item :users="JSON.parse(item.oldValue)"></sd-user-item>
                            </template>
                            <template v-else>
                              {{ item.oldValue }}
                            </template></span
                          >改为</template
                        >
                        <span :class="$style.newVal">
                          <template
                            v-if="
                              item.fieldName === 'joinEndTime' || item.fieldName === 'joinStartTime'
                            "
                          >
                            {{ parseInt(item.newValue, 10) | sdDateFormat('YYYY-MM-DD') }}
                          </template>
                          <template v-else-if="item.fieldName === 'userType'">
                            {{ getUserType(item.newValue) }}
                          </template>
                          <template v-else-if="item.fieldName === 'userId'">
                            <sd-user-item :users="JSON.parse(item.newValue)"></sd-user-item>
                          </template>
                          <template v-else>
                            {{ item.newValue }}
                          </template>
                        </span>
                      </template>
                    </div>
                  </div>
                </span>
              </td>
            </tr>
          </table> -->

          <!-- </template>
            </audit-advanced-group> -->
          <!-- </td>
        </tr>
      </table> -->
          <!-- 选择人员组件 -->
        </template>
      </sd-detail-form>
    </a-spin>
  </div>
</template>

<script>
import moment from 'moment'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { Message, Modal } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import AuditProjectuserService from '@product/iam/audit/work/projectuser/audit-projectuser-service'
import systemManage from '@/system-manage/system-manage'
import TableColumnTypes from '@/common/services/table-column-types'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import auditAdvancedGroup from '../../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../../components/audit-advanced-group-mixins'
import xmChildTableMixins from '../../../components/xm-child-table-mixins'
import components from './_import-components/audit-projectuser-list-import'
export default {
  name: 'AuditProjectuserList',
  metaInfo: {
    title: '项目成员',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    sdUserPicker,
  },
  mixins: [auditAdvancedGroupMixins, xmChildTableMixins],
  data() {
    return {
      isdelete: false,
      tablekey: 0,
      spinning: false,
      rychange: true,
      pageId: 'audit/project/iamAuditProject',
      projectId: '',
      projectStatus: '',
      waterMark: systemManage.getFormWaterMark(),
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '姓名',
          dataIndex: 'userId',
          width: '150px',
        },
        {
          title: '姓名',
          dataIndex: 'userName',
          sdHidden: true,
        },
        {
          title: '项目角色',
          dataIndex: 'userType',
          width: '150px',
        },
        {
          title: '参与开始日期',
          dataIndex: 'joinStartTime',
          sdRender: TableColumnTypes.date,
          width: '150px',
        },
        {
          title: '参与结束日期',
          dataIndex: 'joinEndTime',
          sdRender: TableColumnTypes.date,
          width: '150px',
        },
        {
          title: '任务说明',
          dataIndex: 'taskExplain',
          width: '18%',
        },
        {
          title: '手机号码',
          dataIndex: 'phoneNumber',
          width: '13%',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          width: '15%',
        },
        {
          title: '人员评分',
          dataIndex: 'userScore',
          width: '15%',
        },
        {
          title: '人员考核排名',
          dataIndex: 'examineResult',
          width: '15%',
          readOnly: true,
          editable: false,
        },
      ],
      modifyLogs: [],
      userRoleOption: {},
      hasLeaderAuthority: false,
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    showSelection(record) {
      if ((record.userType === '04') | (record.userType === '05')) {
        return false
      }
      return true
    },
    // 更新保存修改记录的json
    modifyLogCustomData(modifyLogData) {
      if (modifyLogData[0].newVal !== undefined) {
        const newVal = JSON.parse(modifyLogData[0].newVal)
        const oldVal = JSON.parse(modifyLogData[0].oldVal)
        newVal.forEach((item) => {
          if (!item.userAccount) {
            item.userAccount = JSON.parse(item.userId)[0].code
            item.userName = JSON.parse(item.userId)[0].name
          }
        })
        oldVal.forEach((item) => {
          if (!item.userAccount) {
            item.userAccount = JSON.parse(item.userId)[0].code
            item.userName = JSON.parse(item.userId)[0].name
          }
        })

        modifyLogData[0].newVal = JSON.stringify(newVal)
        modifyLogData[0].oldVal = JSON.stringify(oldVal)
      }

      return modifyLogData
    },
    // 获取json数据
    getValue(valueStr, typeStr) {
      if (typeStr === 'userType') {
        // 修改角色
        return this.userRoleOption[valueStr]
      } else if (typeStr === 'userId') {
        // 修改用户
        if (valueStr === '[]') return ''
        return JSON.parse(valueStr)[0].name
      } else if ((typeStr === 'joinStartTime') | (typeStr === 'joinEndTime')) {
        // 修改时间
        return moment(parseInt(valueStr, 10)).format('YYYY-MM-DD')
      } else {
        return valueStr
      }
    },
    getUserType(userType) {
      return this.userRoleOption[userType]
    },
    initData() {
      const projectId = this.$route.query.projectId
      if (projectId) {
        this.projectId = projectId
      }
      // 初始化操作权限
      this.initOperatePermissions()
      // 加载项目成员变更信息记录
      this.loadUserChangeInfo()
      // 获取角色字典
      AuditProjectuserService.getDictionary('PROJECT_ROLE').then((res) => {
        if (res.data) {
          res.data.forEach((item) => {
            this.userRoleOption[item.id] = item.name
          })
        }
      })
    },
    // 查看当前登录人是否项目成员，如果同时是项目阅读人员，取最大权限（项目成员权限）
    inProjectUser(userList) {
      var isProjectUser = false
      userList.map((item) => {
        if (item.userAccount === getUserInfo().account) {
          isProjectUser = true
          return isProjectUser
        }
      })
      return isProjectUser
    },
    // 初始化操作权限
    initOperatePermissions() {
      axios({
        url: `api/xcoa-mobile/v1/iamauditproject/getProjectInfoById?id=` + this.projectId,
      }).then((res) => {
        const projectStatus = res.data.itemStatus
        const readAuthorityCodes = res.data.readAuthorityCodes
        const userList = res.data.iamProjectUserList
        var isProjectUser = this.inProjectUser(userList)
        // 判断是否拥有项目主审的权限
        if (userList) {
          const currentUserType = userList.map((item) => {
            if (item.userAccount === getUserInfo().account) {
              return item.userType
            } else {
              return false
            }
          })
          // 只有项目组长和项目副组长可以操作
          if (currentUserType.indexOf('01') > -1 || currentUserType.indexOf('05') > -1) {
            this.hasLeaderAuthority = true
          }
        }
        // 判断是否拥有操作的权限
        if (projectStatus === '05' || projectStatus === '07') {
          this.hasLeaderAuthority = false
        } else {
          if (
            readAuthorityCodes != null &&
            readAuthorityCodes.indexOf(getUserInfo().account) > -1 &&
            !isProjectUser
          ) {
            this.hasLeaderAuthority = false
          }
        }
      })
    },
    loadUserChangeInfo() {
      // PROJECT_ROLE
      AuditProjectuserService.getUserChangeLogInfo(this.projectId).then((res) => {
        if (res.data) {
          // fieldName=add 标识添加人 fieldDesc为全部内容
          // fieldName=delete 标识删除人 fieldDesc为全部内容
          // 其余 fieldName 标识更新信息，fieldDesc为字段中文名 newValue为新值 oldValue为旧值
          const modifyLogs = []
          res.data
            .sort(function(a, b) {
              return b.creationTime - a.creationTime
            })
            .forEach((item) => {
              item.xt =
                item.creatorName + '_' + moment(item.creationTime).format('YYYY-MM-DD HH:mm:ss')
              const i = modifyLogs.find((n) => n.xt === item.xt)
              if (item.newValue === null) {
                item.newValue = ''
              }
              if (item.oldValue === null) {
                item.oldValue = ''
              }
              if (i !== undefined) {
                // 增加变更人姓名层级  如果存在则直接追加
                if (!i.xx[item.modifiedUserName]) {
                  i.xx[item.modifiedUserName] = [
                    {
                      changeUser: item.modifiedUserName,
                      fieldDesc: item.fieldDesc,
                      fieldName: item.fieldName,
                      newValue: item.newValue,
                      oldValue: item.oldValue,
                    },
                  ]
                } else {
                  i.xx[item.modifiedUserName].push({
                    changeUser: item.modifiedUserName,
                    fieldDesc: item.fieldDesc,
                    fieldName: item.fieldName,
                    newValue: item.newValue,
                    oldValue: item.oldValue,
                  })
                }
              } else {
                item.xx = {}
                item.xx[item.modifiedUserName] = [
                  {
                    changeUser: item.modifiedUserName,
                    fieldDesc: item.fieldDesc,
                    fieldName: item.fieldName,
                    newValue: item.newValue,
                    oldValue: item.oldValue,
                  },
                ]
                modifyLogs.push(item)
              }
            })
          // 将内容继续组装，分到姓名下

          this.modifyLogs = modifyLogs
        }
      })
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    saved() {
      // 保存成功后
      if (!this.isdelete) {
        Message.success({ content: '保存成功', key: 'messagekey' })
      }
      this.isdelete = false
      // 更新修改记录快照
      axios({
        url: 'api/xcoa-mobile/v1/iamprojectuser/updateUserExamineResult',
        method: 'get',
        params: {
          projectId: this.projectId,
        },
      }).then(() => {
        // 更新修改记录
        this.loadUserChangeInfo()
        axios({
          url: 'api/xcoa-mobile/v1/page/wp/' + this.pageId,
          method: 'get',
          params: {
            id: this.projectId,
          },
        }).then((res) => {
          const iamProjectUserList = JSON.parse(
            res.data.pageFormData.pageFieldInfos.find((item) => {
              return item.name === 'iamProjectUserList'
            }).value
          )
          const curIamProjectUserList = this.$refs.form.getFieldValue('iamProjectUserList')
          if (curIamProjectUserList) {
            iamProjectUserList.forEach((item, index) => {
              curIamProjectUserList[index].examineResult = item.examineResult
              curIamProjectUserList[index].id = item.id
            })
          }
          this.$refs.form.setFieldValue('iamProjectUserList', curIamProjectUserList)
          this.$refs.form.dataWhenLoad.find((item) => {
            return item.name === 'iamProjectUserList'
          }).value = JSON.stringify(this.$refs.form.getFieldValue('iamProjectUserList'))
          this.spinning = false
        })
      })
    },
    // 保存
    saveForm() {
      this.$refs.tabaData.save()
    },
    saveChange(arg) {
      AuditProjectuserService.checkOperatorAuthority(this.projectId).then((res) => {
        if (res.data) {
        }
      })
      const data = this.$refs.form.getFieldValue('iamProjectUserList')
      this.$refs.form.setFieldValue('iamProjectUserList', data)
      this.spinning = true
      this.$refs.form.saveBtnClick()
    },
    // 删除提示
    deletedFun() {
      // 删除标记位
      this.isdelete = true
      Message.success({ content: '删除成功', key: 'messagekey' })
    },
    // 打开选择人员的组件
    openProjectUserSelect() {
      this.$refs.projectUserSelect.openPicker()
    },
    //
    projectUserChange(val) {
      this.spinning = true
      const sl = new Date(this.$refs.form.getFieldValue('planStartTime')).getTime()
      const el = new Date(this.$refs.form.getFieldValue('planEndTime')).getTime()
      const userList = val.map((item) => {
        return {
          id: null,
          joinEndTime: el,
          joinStartTime: sl,
          projectId: this.$route.query.record,
          userAccount: item.code,
          userId:
            '[{"code":"' +
            item.code +
            '","name":"' +
            item.name +
            '","text":"' +
            item.name +
            '","type":"User"}]',
          userName: item.name,
          userType: '03',
        }
      })
      // 获取电话号码及邮箱
      userList.forEach((item, index) => {
        axios({
          url:
            'api/xcoa-mobile/v1/iamuserbase/getUserBaseInfoByAccount?userAccount=' +
            item.userAccount,
          method: 'get',
        }).then((res) => {
          if (res.data.userMobile === null) {
            item.phoneNumber = ''
          } else {
            item.phoneNumber = res.data.userMobile
          }
          if (res.data.userMail === null) {
            item.email = ''
          } else {
            item.email = res.data.userMail
          }
          // 最后一次循环，赋值
          if (index === userList.length - 1) {
            let oldUserList = this.$refs.form.getFieldValue('iamProjectUserList')
            oldUserList = oldUserList.concat(userList)
            this.$refs.form.setFieldValue('iamProjectUserList', oldUserList)
            this.spinning = false
          }
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';

:global(.ant-checkbox-group > label:first-child) {
  margin-left: 9px !important;
}

:global(.title_sd-detail-form_common) {
  visibility: hidden;
}

.form {
  :global(.buttons_sd-detail-form_common) {
    visibility: hidden;
  }
  :global(.ant-spin-container) {
    margin-top: 0 !important;
  }
}

.oldVal,
.newVal {
  margin: 0 5px;
}

.tablexm tr td {
  border: none !important;
}

.change-user {
  vertical-align: top;
}
.add-btn {
  position: absolute;
  top: 5px;
  right: 85px;
  z-index: 99;
}
</style>
