<template>
  <div>
    <a-spin :spinning="spinning">
      <sd-detail-form
        ref="form"
        v-sd-watermark="waterMark"
        :page-id="pageId"
        form-id="icEvaluationPlan"
        :record-id="this.$route.query.planId ? parseInt(this.$route.query.planId) : null"
        :class="$style.form"
        @saved="saved"
        @close="close(true)"
        @sdFormReady="sdFormReady"
        @modifyLogCustomData="modifyLogCustomData"
      >
        <template v-slot="{ model, fields }">
          <table>
            <tr>
              <sd-form-item-td name="icEvaluationPlanUserList" :colspan="4" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group :group-label="'人员信息'">
                    <template>
                      <!-- 添加按钮，打开选人组件 -->
                      <a-button
                        v-if="model.creatorName === curuser && initparams(model, fields)"
                        type="link"
                        :class="$style.addBtn"
                        @click="openPlanUserSelect"
                      >
                        <a-icon type="plus-circle" :theme="'filled'" />
                        添加
                      </a-button>
                      <iam-audit-user-child-table
                        :key="tablekey"
                        ref="tabaData"
                        v-model="model.icEvaluationPlanUserList"
                        :addbuttonvisiable="false"
                        :class="$style.deptPlanChild"
                        label=""
                        :fields="Array.from(fields.icEvaluationPlanUserList.attr.dync)"
                        :savebuttonvisiable="false"
                        :columns="columns"
                        :dzcl="true"
                        :read-only="model.creatorName !== curuser"
                        :patch-save="true"
                        @change="saveChange"
                        @deleted="deletedFun"
                      >
                      </iam-audit-user-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item-td>
            </tr>
          </table>

          <!-- 选人组件 -->
          <div v-show="false">
            <sd-user-picker
              ref="planUserSelect"
              :single="false"
              :read-only="false"
              @change="planUserChange"
            />
          </div>
          <div
            v-if="model.creatorName === curuser"
            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>

          <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>
        </template>
      </sd-detail-form>
    </a-spin>
  </div>
</template>

<script>
import moment from 'moment'
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { Message, Modal } from 'ant-design-vue'
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 MtxEvaluationService from '@product/iam/ic/evaluation/ic-evaluation-service'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import xmChildTableMixins from '@product/iam/components/xm-child-table-mixins'
import components from './_import-components/ic-planuser-list-import'
export default {
  name: 'IcPlanuserList',
  metaInfo: {
    title: '评价人员',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    sdUserPicker,
  },
  mixins: [auditAdvancedGroupMixins, xmChildTableMixins],
  data() {
    return {
      isdelete: false,
      tablekey: 0,
      spinning: false,
      rychange: true,
      pageId: 'ic/evaluation/plan/icEvaluationPlan',
      planId: '',
      projectStatus: '',
      waterMark: systemManage.getFormWaterMark(),
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '姓名',
          dataIndex: 'contactsAccount',
          width: '150px',
          sdHidden: true,
        },
        {
          title: '姓名',
          dataIndex: 'contactsOpt',
        },
        {
          title: '人员角色',
          dataIndex: 'contactsRole',
          width: '150px',
        },
        {
          title: '内容描述',
          dataIndex: 'contentDesc',
        },
        { dataIndex: 'contactsName', sdHidden: true },
      ],
      modifyLogs: [],
      userRoleOption: {},
      // hasLeaderAuthority: true,
      curuser: '',
      mode: null,
      flag: true,
    }
  },
  mounted() {
    const userInfo = getUserInfo()
    this.curuser = userInfo.name
    this.initData()
  },
  methods: {
    initparams(model, fields) {
      if (this.flag) {
        fields.icEvaluationPlanUserList.readonly = false
        fields.icEvaluationPlanUserList.attr.dync.forEach((i) => {
          i.readonly = false
        })
        this.flag = false
      }
      return true
    },
    // 页面加载完成后
    sdFormReady() {
      this.mode = this.$refs.form.formData.mode
      // 如果是转入，则直接是VIEW
      const index = this.$refs.form.formData.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'creatorName'
      )
      if (this.$refs.form.formData.pageFormData.pageFieldInfos[index].value === this.curuser) {
        this.mode = 'EDIT'
        this.$refs.form.formData.mode = 'EDIT'
      }
    },
    // 更新保存修改记录的json
    modifyLogCustomData(modifyLogData) {
      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 === 'contactsRole') {
        // 角色
        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 planId = this.$route.query.planId
      if (planId) {
        this.planId = planId
      }
      // 初始化操作权限
      // this.initOperatePermissions()
      // 加载项目成员变更信息记录
      this.loadUserChangeInfo()
      // 获取角色字典
      AuditProjectuserService.getDictionary('CONTACTS_ROLE').then((res) => {
        if (res.data) {
          res.data.forEach((item) => {
            this.userRoleOption[item.id] = item.name
          })
        }
      })
    },
    loadUserChangeInfo() {
      // PROJECT_ROLE
      MtxEvaluationService.getUserChangeLogInfo(this.planId).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) => {
              if (['contactsAccount', 'contactsOpt'].indexOf(item.fieldName) < 0) {
                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
      // 更新修改记录
      this.loadUserChangeInfo()
      // 更新修改记录快照
      axios({
        url: 'api/xcoa-mobile/v1/page/wp/' + this.pageId,
        method: 'get',
        params: {
          id: this.planId,
        },
      }).then((res) => {
        const icEvaluationPlanUserList = JSON.parse(
          res.data.pageFormData.pageFieldInfos.find((item) => {
            return item.name === 'icEvaluationPlanUserList'
          }).value
        )

        const curicEvaluationPlanUserList = this.$refs.form.getFieldValue(
          'icEvaluationPlanUserList'
        )
        if (curicEvaluationPlanUserList) {
          icEvaluationPlanUserList.forEach((item, index) => {
            curicEvaluationPlanUserList[index].id = item.id
          })
        }
        this.$refs.form.setFieldValue('icEvaluationPlanUserList', curicEvaluationPlanUserList)

        this.$refs.form.dataWhenLoad.find((item) => {
          return item.name === 'icEvaluationPlanUserList'
        }).value = JSON.stringify(this.$refs.form.getFieldValue('icEvaluationPlanUserList'))
        this.spinning = false
      })
    },
    // 保存
    saveForm() {
      const ulist = this.$refs.form.getFieldValue('icEvaluationPlanUserList')
      // 校验每一行都要有人员和角色
      let flag = true
      ulist.forEach((i) => {
        if (
          i.contactsOpt === undefined ||
          i.contactsOpt.length === 0 ||
          i.contactsRole === undefined
        ) {
          flag = false
        }
      })
      if (!flag) {
        Modal.warning({
          title: '提示',
          content: '请完善评价人员中的人员和角色信息!',
        })
      } else {
        const nulist = []
        ulist.forEach((i) => {
          const opt = JSON.parse(i.contactsOpt)
          nulist.push({
            id: i.id,
            planId: i.planId,
            contactsAccount: opt[0].code,
            contactsOpt: i.contactsOpt,
            contactsName: opt[0].name,
            contactsRole: i.contactsRole,
            contentDesc: i.contentDesc,
          })
        })
        this.$refs.form.setFieldValue('icEvaluationPlanUserList', nulist)
        this.$refs.tabaData.save()
      }
    },
    saveChange(arg) {
      AuditProjectuserService.checkOperatorAuthority(this.planId).then((res) => {
        if (res.data) {
        }
      })
      const data = this.$refs.form.getFieldValue('icEvaluationPlanUserList')
      this.$refs.form.setFieldValue('icEvaluationPlanUserList', data)
      this.spinning = true
      this.$refs.form.saveBtnClick()
    },
    // 删除提示
    deletedFun() {
      // 删除标记位
      this.isdelete = true
      Message.success({ content: '删除成功', key: 'messagekey' })
    },
    // 打开选择人员的组件
    openPlanUserSelect() {
      this.$refs.planUserSelect.openPicker()
    },
    //
    planUserChange(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,
          planId: this.$route.query.planId,
          contactsAccount: item.code,
          contactsOpt:
            '[{"code":"' +
            item.code +
            '","name":"' +
            item.name +
            '","text":"' +
            item.name +
            '","type":"User"}]',
          contactsName: item.name,
        }
      })
      let oldUserList = this.$refs.form.getFieldValue('icEvaluationPlanUserList')
      if (oldUserList) {
        oldUserList = oldUserList.concat(userList)
      } else {
        oldUserList = userList
      }
      this.$refs.form.setFieldValue('icEvaluationPlanUserList', oldUserList)
      this.spinning = false
      // 获取电话号码及邮箱
      // 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) {

      //     }
      //   })
      // })
    },
  },
}
</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: 0px !important;
  }
}

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

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

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