<template>
  <div :class="$style.warp">
    <sd-form
      ref="form"
      :key="updateKey"
      :init-values="basicValues.concat(briefValues)"
      :read-only="!editable"
      :class="$style.form"
    >
      <template v-slot="{ model }">
        <a-divider>基本信息</a-divider>
        <table>
          <colgroup>
            <col width="15%" />
            <col width="35%" />
            <col width="15%" />
            <col width="35%" />
          </colgroup>
          <tr
            v-for="rowBasic in Math.ceil(basicValues.length / columnNum)"
            :key="rowBasic + 'basic'"
          >
            <sd-form-item-td
              v-for="item in basicValuesMap[rowBasic - 1]"
              :key="item"
              :name="item"
              :input-props="{
                type: ['password', 'repassword'].indexOf(item) > -1 ? 'password' : '',
              }"
            >
              <template
                v-if="['parentId', 'roles', 'account', 'statusName'].indexOf(item) > -1"
                v-slot:read-and-edit
              >
                <template v-if="item === 'parentId'">
                  <!-- 选部门-->
                  <sd-value-picker
                    v-if="editable"
                    v-model="model.parentId"
                    single
                    option-value="key"
                    option-label="title"
                  >
                    <template v-slot="scope">
                      <sd-picker-source-tree :load-tree-data="onLoadTreeData" v-bind="scope" />
                    </template>
                  </sd-value-picker>
                  <template v-else> {{ model.parentId && model.parentId[0].title }} </template>
                </template>
                <template v-if="item === 'roles'">
                  <!-- 一直不可编辑 -->
                  <div :class="$style['auth-roles']">
                    {{
                      userRoles
                        ? userRoles
                            .map((item) => {
                              return item.name
                            })
                            .join(',')
                        : ''
                    }}
                  </div>
                </template>
                <template v-if="item === 'account'">
                  <!-- 只有新建的时候可编辑 -->
                  <template v-if="unid">
                    {{ model.account }}
                  </template>
                  <template v-else>
                    <a-input v-model="model.account"></a-input>
                  </template>
                </template>
                <template v-if="item === 'statusName'">
                  <!-- （三员）安全管理员 或（非三员）系统管理员可编辑 -->
                  <!-- <template v-if="!isSecAdmin">
                    {{ model.statusName }}
                  </template>
                  <template v-else>
                    <a-select v-model="model.statusName" :options="statusNameOpts" />
                  </template> -->
                  <a-select v-model="model.statusName" :options="statusNameOpts" />
                </template>
              </template>
            </sd-form-item-td>
          </tr>
        </table>

        <a-divider>详细信息</a-divider>
        <table>
          <colgroup>
            <col width="15%" />
            <col width="35%" />
            <col width="15%" />
            <col width="35%" />
          </colgroup>
          <tr
            v-for="rowBrief in Math.ceil(briefValues.length / columnNum)"
            :key="rowBrief + 'brief'"
          >
            <sd-form-item-td
              v-for="item in briefValuesMap[rowBrief - 1]"
              :key="item"
              :name="item"
              :label="isAdjunctUser && item === 'adjunctPathNames' ? '主职部门' : undefined"
            >
              <template
                v-if="
                  ['userSsoInfos', 'chargeGroup', 'adjunctPathNames', 'classified'].indexOf(item) >
                    -1
                "
                v-slot:read-and-edit
              >
                <template v-if="item === 'userSsoInfos'">
                  <template v-if="!editable">
                    <sd-table
                      v-if="userSsoInfos && userSsoInfos.length !== 0"
                      :columns="userSsoInfosColumns"
                      sortable
                      :data-source.sync="userSsoInfos"
                      :pagination="false"
                      row-key="id"
                    >
                    </sd-table>
                    <template v-else><span></span></template>
                  </template>
                  <template v-else>
                    <a-button class="editable-add-btn" @click="addSso">
                      添加
                    </a-button>
                    <sd-table
                      v-if="userSsoInfos && userSsoInfos.length !== 0"
                      :columns="userSsoInfosColumns"
                      sortable
                      :data-source.sync="userSsoInfos"
                      :pagination="false"
                      row-key="id"
                      :custom-row="
                        (record, index) => {
                          return {
                            on: {
                              click: (event) => {
                                rowClickUserSso(record)
                              },
                            },
                          }
                        }
                      "
                    >
                    </sd-table>
                    <template v-else><span></span></template>
                  </template>
                </template>
                <template v-if="item === 'adjunctPathNames'">
                  <template v-if="isAdjunctUser">
                    {{
                      preResponseData.props.adjunctInfo &&
                        JSON.parse(preResponseData.props.adjunctInfo).masterDeptName
                    }}
                  </template>
                  <template v-else>
                    <!-- 选部门-->
                    <sd-value-picker
                      v-if="editable"
                      v-model="model.adjunctPathNames"
                      :disabled-keys="model.parentId ? [model.parentId[0].key] : []"
                      option-value="key"
                      option-label="title"
                    >
                      <template v-slot="scope">
                        <sd-picker-source-tree :load-tree-data="onLoadTreeData" v-bind="scope" />
                      </template>
                    </sd-value-picker>
                    <template v-else>
                      {{
                        model.adjunctPathNames &&
                          model.adjunctPathNames
                            .map((item) => {
                              return item.title
                            })
                            .join(',')
                      }}
                    </template>
                  </template>
                </template>
                <template v-if="item === 'authorizedRoleNames'">
                  <div :class="$style['auth-roles']">
                    {{ model.authorizedRoleNames }}
                  </div>
                </template>
                <template v-if="item === 'authorizedGroupNames'">
                  <div :class="$style['auth-roles']">
                    {{ model.authorizedGroupNames }}
                  </div>
                </template>
                <template v-if="item === 'chargeGroup'">
                  <!-- 选部门-->
                  <sd-value-picker
                    v-if="editable"
                    v-model="model.chargeGroup"
                    option-value="key"
                    option-label="title"
                    @change="
                      (values) => {
                        changeValuePick(values, 'chargeGroup')
                      }
                    "
                  >
                    <template v-slot="scope">
                      <sd-picker-source-tree :load-tree-data="onLoadTreeData" v-bind="scope" />
                    </template>
                  </sd-value-picker>
                  <template v-else>
                    {{
                      model.chargeGroup &&
                        model.chargeGroup
                          .map((item) => {
                            return item.title
                          })
                          .join(',')
                    }}
                  </template>
                </template>
                <template v-if="item === 'classified'">
                  <template v-if="!isSecAdmin">
                    {{ getClassify(model.classified) && getClassify(model.classified).label }}
                  </template>
                  <template v-else>
                    <a-select v-model="model.classified" :options="classifyOpts" />
                  </template>
                </template>
              </template>
            </sd-form-item-td>
          </tr>
        </table>

        <a-divider v-if="!isBatch">单点登录</a-divider>
        <a-row v-if="!isBatch" :class="$style['no-label']">
          <a-col :span="24">
            <sd-form-item name="userSsoInfos" :label="null">
              <template v-slot:read-and-edit>
                <template v-if="!editable">
                  <sd-table
                    v-if="userSsoInfos && userSsoInfos.length !== 0"
                    :columns="userSsoInfosColumns"
                    sortable
                    :data-source.sync="userSsoInfos"
                    :pagination="false"
                    row-key="id"
                  >
                  </sd-table>
                  <template v-else><span></span></template>
                </template>
                <template v-else>
                  <div :class="$style.operationWrapper">
                    <a-space>
                      <a-button class="editable-add-btn" @click="addSso">
                        添加
                      </a-button>
                      <a-button
                        class="editable-delete-btn"
                        :disabled="ssoSelectedRowKeys.length === 0"
                        @click="deleteSso"
                      >
                        删除
                      </a-button>
                    </a-space>
                  </div>
                  <sd-table
                    ref="ssoTable"
                    :columns="userSsoInfosColumns"
                    sortable
                    :data-source.sync="userSsoInfos"
                    :pagination="false"
                    row-key="id"
                    :row-selection="{
                      selectedRowKeys: ssoSelectedRowKeys,
                      onChange: ssoSelectedChange,
                    }"
                    :custom-row="
                      (record, index) => {
                        return {
                          on: {
                            click: (event) => {
                              rowClickUserSso(record)
                            },
                          },
                        }
                      }
                    "
                  >
                  </sd-table>
                </template>
              </template>
            </sd-form-item>
          </a-col>
        </a-row>
      </template>
    </sd-form>
    <a-modal
      v-model="ssoVisible"
      title="增加属性"
      destroy-on-close
      v-bind="{ width: 800 }"
      :mask-closable="false"
      @ok="saveSSO"
      @cancel="$emit('closed')"
    >
      <sd-form ref="ssoForm" :init-values="ssoValues">
        <template>
          <sd-form-item name="ssoSite" />
          <sd-form-item name="ssoId" />
        </template>
      </sd-form>
    </a-modal>
  </div>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import { sdLocalStorage } from '@/common/services/storage-service'
import moment from 'moment'
import { message } from 'ant-design-vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-user-import'
import axios from '@/common/services/axios-instance'

export default {
  name: 'SdOrgUser',
  metaInfo: {
    title: 'SdOrgUser',
  },
  components,
  mixins: [storeMixin],
  props: {
    unid: {
      type: String,
      default: function() {
        return null
      },
    },
    curParent: {
      type: Object,
      default: function() {
        return null
      },
    },
    editable: {
      type: Boolean,
      default: function() {
        return true
      },
    },
    isBatch: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ssoVisible: false,
      columnNum: 2,
      parentInfo: null,
      updateKey: 0,
      userSsoInfosColumns: [
        {
          title: '属性名称',
          dataIndex: 'ssoSite',
        },
        {
          title: '属性值',
          dataIndex: 'ssoId',
        },
      ],
      userRoles: [],
      userSsoInfos: [],

      ssoSelectedRowKeys: [],
      ssoValues: [
        {
          name: 'id',
          caption: 'id',

          dataType: 'string',
        },
        {
          name: 'ssoSite',
          caption: '属性名称',
          required: true,
          dataType: 'string',
        },
        {
          name: 'ssoId',
          caption: '属性值',
          dataType: 'string',
          required: true,
        },
      ],
      briefValues: [
        // {
        //   name: 'idcard',
        //   caption: '身份证',
        //   dataType: 'string',
        // },

        {
          name: 'adjunctPathNames',
          caption: '兼职部门',
          dataType: 'string',
        },
        {
          name: 'mobile',
          caption: '手机',
          dataType: 'string',
        },
        {
          name: 'chargeGroup',
          caption: '分管机构',
          dataType: 'array',
        },
        {
          name: 'room',
          caption: '地址',
          dataType: 'string',
        },

        {
          name: 'email',
          caption: '邮箱',
          dataType: 'string',
          attr: {
            // eslint-disable-next-line no-useless-escape
            regex: /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/,
            regexMessage: '格式有误',
          },
        },
        {
          name: 'authorizedGroupArr',
          caption: '管理机构',
          dataType: 'selectperson',
          attr: {
            selectionType: 'GROUP',
          },
        },
        {
          name: 'phone',
          caption: '电话',
          dataType: 'string',
        },
        {
          name: 'authorizedRoleArr',
          caption: '管理角色',
          dataType: 'selectperson',
          attr: {
            selectionType: 'ROLE',
          },
        },
        {
          name: 'pinyin',
          caption: '姓名拼音',
          dataType: 'string',
        },
        {
          name: 'weight',
          caption: '排序号',
          dataType: 'number',
        },
        {
          name: 'description',
          caption: '备注信息',
          dataType: 'string',
        },
        {
          name: 'isShow',
          caption: '是否展示',

          dataType: 'number',
          value: '1',
          attr: {
            defaultValue: '1',
            selectListItem: [
              {
                value: '1',
                label: '是',
              },
              {
                value: '0',
                label: '否',
              },
            ],
          },
        },
        {
          name: 'classified',
          caption: '密级',

          dataType: 'string',

          attr: {
            defaultValue: '',
            selectListItem: [
              {
                value: '1',
                label: '是',
              },
              {
                value: '0',
                label: '否',
              },
            ],
          },
        },
        {
          name: 'userSsoInfos',
          caption: '单点登录',
          dataType: 'string',
        },
      ],
      basicValues: [
        {
          name: 'name',
          caption: '姓名',
          required: true,
          dataType: 'string',
        },
        {
          name: 'account',
          caption: '账号',
          dataType: 'string',
          required: true,
        },
        {
          name: 'parentId',
          caption: '部门',
          dataType: 'string',
          required: true,
        },
        {
          name: 'password',
          caption: '密码',
          dataType: 'string',
          required: true,
        },
        {
          name: 'level',
          caption: '职务',
          dataType: 'selectlist',
          value: null,
          attr: {
            selectListItem: [],
          },
        },
        {
          name: 'repassword',
          caption: '重复密码',
          dataType: 'string',
          required: true,
        },
        {
          name: 'roles',
          caption: '角色',
          dataType: 'string',
        },
        {
          name: 'statusName',
          caption: '状态',
          dataType: 'string',
          attr: {
            defaultValue: '正常',
          },
        },
      ],
      props: {},
      preResponseData: {
        props: {},
      },
      loadingMsg: null,
      classifyOpts: [],
      statusNameOpts: [
        {
          key: '正常',
          title: '正常',
        },
        {
          key: '停用',
          title: '停用',
        },
        {
          key: '注销',
          title: '注销',
        },
      ],
      isAdjunctUser: false,
    }
  },
  computed: {
    basicValuesMap() {
      const values = []
      const srcValues = this.basicValues
      const columnNum = this.columnNum

      srcValues.forEach((item, index) => {
        // console.log(index, '/', columnNum, ' == ', index / columnNum)
        // console.log(Math.floor(index / columnNum))
        if (values[Math.floor(index / columnNum)]) {
        } else {
          values[Math.floor(index / columnNum)] = []
        }
        values[Math.floor(index / columnNum)][index % columnNum] = item.name
      })

      return values
    },
    briefValuesMap() {
      const values = []
      const srcValues = this.briefValues
      const columnNum = this.columnNum

      srcValues
        .filter((item) => {
          return item.name !== 'userSsoInfos'
        })
        .forEach((item, index) => {
          if (values[Math.floor(index / columnNum)]) {
          } else {
            values[Math.floor(index / columnNum)] = []
          }
          values[Math.floor(index / columnNum)][index % columnNum] = item.name
        })

      return values
    },
    isSecAdmin() {
      let roles = []
      const openSecret = JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').openSecret
      // 开启三员时，直接判断是否为安全管理员
      if (openSecret) {
        roles = ['SECURITYADMINISTRATOR', 'SUB_SECURITY_ADMIN']
      } else {
        // 未开启三员时，判断是否为系统管理员
        roles = ['ADMINISTRATOR', 'SUB_ADMIN']
      }
      return this.userInfo.roles.some((item) => {
        return roles.indexOf(item.code) > -1
      })
    },
    batchFields() {
      // 批量修改，只能修改部门、职务、帐号状态、是否展示；非安全管理员权限（开启三员时，系统管理员角色的用户），不可修改状态字段
      const fields = ['parentId', 'level', 'isShow']
      if (this.isSecAdmin) {
        fields.push('statusName')
      }
      return fields
    },
  },

  watch: {
    unid: {
      handler(newVal, oldVal) {
        this.getByStep()
      },
      immediate: true,
    },
  },
  created() {
    // 批量修改
    if (this.isBatch) {
      this.basicValues = this.basicValues.filter((f) => this.batchFields.includes(f.name))
      this.briefValues = this.briefValues.filter((f) => this.batchFields.includes(f.name))
    }
    axios.get('api/admin/flow-mobile/v1/user-classified/info').then((res) => {
      const classified = res.data
      this.classified = res.data
      this.message = `密码必须有 ${classified.includeLower ? '小写字母' : ''} ${
        classified.includeUpper ? '大写字母' : ''
      } ${classified.includeNum ? '数字' : ''} ${classified.includeSpecialChar ? '特殊字符' : ''} ${
        classified.minLength ? `最小${classified.minLength}位字符` : ''
      }`
    })
  },
  methods: {
    handlePass(value, account) {
      var message = 'success'
      if (account && value && value.indexOf(account) !== -1) {
        message = '密码不能包含用户名'
        return message
      }

      if (value && this.classified) {
        if (this.classified.minLength && value.length < this.classified.minLength) {
          message = this.message
        }
        if (this.classified.includeLower && !value.match(/[a-z]+/)) {
          message = this.message
        }
        if (this.classified.includeUpper && !value.match(/[A-Z]+/)) {
          message = this.message
        }
        if (this.classified.includeNum && !value.match(/[0-9]+/)) {
          message = this.message
        }
        if (
          this.classified.includeSpecialChar &&
          !value.match(/[`~!@#$%^&*()_+<>?:"{},.\\/;'[\]]/)
        ) {
          message = this.message
        }
      }
      return message
    },
    ssoSelectedChange(selectedRowKeys) {
      this.ssoSelectedRowKeys = selectedRowKeys
    },
    deleteSso() {
      const ids = this.ssoSelectedRowKeys
      this.userSsoInfos = this.userSsoInfos.filter((item) => {
        return ids.indexOf(item.id) === -1
      })
      this.ssoSelectedRowKeys = []
    },
    addSso() {
      this.ssoVisible = true
      this.ssoValues.forEach((item) => {
        item.value = ''
        if (item.name === 'id') {
          item.value = parseInt('-' + moment().format('YYYYMMDDhhmmss'), 10)
        }
      })
    },

    rowClickUserSso(record) {
      this.ssoVisible = true
      this.ssoValues.forEach((item) => {
        item.value = record[item.name]
      })
    },
    saveSSO() {
      return new Promise((resolve) => {
        this.$refs.ssoForm.validateFields().then((success) => {
          if (success) {
            const values = this.$refs.ssoForm.getFieldsValue()
            if (values.id < 0) {
              values.id = Math.abs(values.id)
              this.userSsoInfos.push({
                ...values,
              })
            } else {
              const sso = this.userSsoInfos.filter((item) => {
                return item.id === values.id
              })[0]
              for (const v in values) sso[v] = values[v]
            }

            this.ssoVisible = false
          }
        })
      })
    },
    getByStep() {
      this.loadingMsg = message.loading({
        key: this.msgKey,
        content: '加载中...',
        duration: 0,
      })
      Promise.all([OrgService.getOrgLevel({ code: 'U' }), OrgService.getClassifyLevel()]).then(
        (allRes) => {
          let res = allRes[0]
          this.basicValues.forEach((item) => {
            if (item.name === 'level')
              item.attr.selectListItem = res.data.datas.map((opt) => {
                return {
                  value: opt.code,
                  label: opt.name,
                }
              })
          })
          res = allRes[1]
          this.briefValues.forEach((item) => {
            if (item.name === 'classified') {
              item.attr.selectListItem = res.data.map((opt) => {
                return {
                  value: opt.value,
                  label: opt.name,
                }
              })
              this.classifyOpts = item.attr.selectListItem.map((opt) => {
                return {
                  key: opt.value,
                  title: opt.label,
                }
              })
            }
          })
          this.updateKey++
          this.getDefaultValue()
        }
      )
    },
    getClassify(classify) {
      if (classify === '') return {}
      const oClassify = this.briefValues
        .find((item) => {
          return item.name === 'classified'
        })
        .attr.selectListItem.find((opt) => {
          return opt.value === classify
        })
      return oClassify
    },
    getDefaultValue() {
      this.isAdjunctUser = false
      if (this.unid) {
        OrgService.getOrgUser({ id: this.unid }).then((res) => {
          const data = res.data
          this.preResponseData = data
          const fieldMap = {}
          this.basicValues.concat(this.briefValues).forEach((item) => {
            fieldMap[item.name] = undefined
            if (item.name === 'level') {
              fieldMap[item.name] = data.props.lev
            } else if (item.name === 'isShow') {
              fieldMap[item.name] = data[item.name].toString()
            } else if (item.name === 'userSsoInfos') {
              fieldMap[item.name] = JSON.stringify(data[item.name])

              this.userSsoInfos = data[item.name]
            } else if (item.name === 'roles') {
              fieldMap[item.name] = JSON.stringify(data[item.name])

              this.userRoles = data[item.name]
            } else if (['adjunctPathNames', 'parentId', 'chargeGroup'].indexOf(item.name) > -1) {
            } else if (item.name === 'password' || item.name === 'repassword') {
              item.required = false
              fieldMap[item.name] = ''
            } else if (item.name === 'classified') {
              fieldMap[item.name] = data.props[item.name] // [{ value: data.props[item.name] }]
            } else if (['authorizedGroupArr', 'authorizedRoleArr'].indexOf(item.name) > -1) {
              if (data.authorizedGroupNames) {
                fieldMap.authorizedGroupArr = data.authorizedGroupNames
                  .split(',')
                  .map((i, index) => {
                    const res = {
                      type: 'Group',
                      code: data.props.authorizedGroups?.split(',')[index],
                      name: i,
                    }
                    return res
                  })
              }
              if (data.authorizedRoleNames) {
                fieldMap.authorizedRoleArr = data.authorizedRoleNames.split(',').map((i, index) => {
                  const res = {
                    type: 'Role',
                    code: data.props.authorizedRoles?.split(',')[index],
                    name: i,
                  }
                  return res
                })
              }
            } else {
              fieldMap[item.name] = data[item.name]
            }
          })

          // 兼职部门
          fieldMap.adjunctPathNames = []
          if (data?.props?.adjunctInfo !== '' && data?.props?.adjunctInfo) {
            const adjunctInfo = JSON.parse(data.props.adjunctInfo)
            fieldMap.adjunctPathNames = adjunctInfo.adjunctDeptIds.map((item, index) => {
              return {
                key: item.toString(),
                title: adjunctInfo.adjunctDeptNames[index],
              }
            })

            if (adjunctInfo.masterUser.account !== data.account) {
              this.isAdjunctUser = true
            }
          }

          // 分管机构
          fieldMap.chargeGroup = []
          if (data?.props?.chargeGroups !== '' && data?.props?.chargeGroups) {
            const chargeGroupIds = data.props.chargeGroups.split(',')
            const chargeGroupCodes = data.props.chargeGroupCodes.split(',')
            const chargeGroupNames = data.props.chargeGroupNames.split(',')
            fieldMap.chargeGroup = chargeGroupIds.map((item, index) => {
              return {
                key: item,
                title: chargeGroupNames[index],
                code: chargeGroupCodes[index],
              }
            })
          }

          fieldMap.parentId = [{ key: data.parentId.toString(), title: data.parentPathName }]
          this.$refs.form.setFieldsValue(fieldMap)

          this.loadingMsg?.()
        })
      } else {
        // 非批量修改
        if (!this.isBatch) {
          // 获取当前部门下用户的最大排序号
          OrgService.getOrgUserList({
            expressions: [
              {
                name: 'parentId',
                op: 'eq',
                dataType: 'str',
                stringValue: this.curParent.id,
              },
            ],
            orderBy: 'weight desc',
            maxResults: 1,
          }).then((res) => {
            const weight = res.data.datas?.[0]?.weight || 0
            this.$refs.form.setFieldValue('weight', weight + 1)
          })
        }
        Promise.all([]).then(() => {
          this.preResponseData = {
            props: {},
          }
          const fieldMap = {}
          this.basicValues.concat(this.briefValues).forEach((item) => {
            if (item.attr?.defaultValue) {
              fieldMap[item.name] = item.attr?.defaultValue
            } else {
              fieldMap[item.name] = undefined
            }
          })
          fieldMap.statusName = '正常'

          fieldMap.parentId = [{ key: this.curParent.id.toString(), title: this.curParent.text }]
          this.$refs.form.setFieldsValue(fieldMap)
          this.loadingMsg?.()
        })
      }
    },
    save(ids) {
      return new Promise((resolve) => {
        let saveFlag = false
        this.$refs.form
          .validateFields()
          .then((success) => {
            if (success) {
              let params = {
                props: {
                  ...this.preResponseData.props,
                },
              }
              const values = this.$refs.form.getFieldsValue()
              if (this.editable) {
                if (values.password && values.repassword && values.password !== values.repassword) {
                  message.error('密码不一致')
                  return resolve(false)
                }
                const mobile = values.mobile
                const phone = values.phone
                const email = values.email

                var phoneP = /^0\d{2,3}-?\d{7,8}$/
                var mobileP = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$/
                var emailP = /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/
                if (mobile) {
                  //  手机号码
                  if (!mobileP.test(mobile)) {
                    message.error('手机号码格式不正确')
                    return resolve(false)
                  }
                }
                if (phone) {
                  // 电话号码
                  if (!(phoneP.test(phone) || mobileP.test(phone))) {
                    message.error('电话号码格式不正确')
                    return resolve(false)
                  }
                }
                if (email) {
                  // 邮箱
                  if (!emailP.test(email)) {
                    message.error('邮箱格式不正确')
                    return resolve(false)
                  }
                }
                const authorizedRoleArr = values.authorizedRoleArr
                const findRoles = function(roleCode) {
                  if (authorizedRoleArr) {
                    for (let i = 0; i < authorizedRoleArr.length; i++) {
                      const c = authorizedRoleArr[i]
                      if (c.code === roleCode) {
                        return 1
                      }
                    }
                  }
                  return 0
                }
                const admin1 = findRoles('ADMINISTRATOR')
                const security1 = findRoles('SECURITYADMINISTRATOR')
                const audit1 = findRoles('SECURITYAUDITOR')
                if (admin1 + security1 + audit1 > 1) {
                  message.error('不能授权多个的管理员角色!')
                  return resolve(false)
                }

                const checkPass = this.handlePass(values.password, values.account)
                if (checkPass !== 'success') {
                  message.error(checkPass)
                  return resolve(false)
                }

                this.$refs.form.getBackendValues().forEach((item) => {
                  switch (item.name) {
                    case 'parentId':
                      params[item.name] = parseInt(JSON.parse(item.value)[0].key, 10)
                      break
                    case 'level':
                      params[item.name] = item.value
                      params.props.lev = item.valuechargeGroup ? item.value : ''
                      break
                    case 'roles':
                      params[item.name] = item.value ? JSON.parse(item.value) : item.value
                      break
                    case 'userSsoInfos':
                      params[item.name] = this.userSsoInfos.map((sso) => {
                        return {
                          ssoSite: sso.ssoSite,
                          ssoId: sso.ssoId,
                        }
                      })
                      break
                    case 'chargeGroup': {
                      // 分管机构是更新props下的如下3个字段
                      if (item.value) {
                        const chargeGroupIds = []
                        const chargeGroupCodes = []
                        const chargeGroupNames = []
                        JSON.parse(item.value).forEach((dep) => {
                          chargeGroupIds.push(dep.key)
                          chargeGroupNames.push(dep.title)
                          chargeGroupCodes.push(dep.code)
                        })
                        params.props.chargeGroups = chargeGroupIds.join()
                        params.props.chargeGroupCodes = chargeGroupCodes.join()
                        params.props.chargeGroupNames = chargeGroupNames.join()
                      }

                      break
                    }
                    case 'adjunctPathNames': {
                      if (item.value) {
                        const curValue = JSON.parse(item.value).map((dep) => {
                          return parseInt(dep.key, 10)
                        })
                        params.adjunctPathNames = JSON.parse(item.value)
                          .map((dep) => {
                            return dep.title
                          })
                          .join(',')
                        let preValue
                        if (
                          this.preResponseData.props?.adjunctInfo !== '' &&
                          this.preResponseData.props?.adjunctInfo
                        ) {
                          preValue = JSON.parse(this.preResponseData.props.adjunctInfo)
                        } else {
                          preValue = {
                            adjunctDeptIds: [],
                            id: 0,
                          }
                        }

                        if (preValue.adjunctDeptIds.join(',') !== curValue.join(',')) {
                          params.changeUserAdjunctParam = {
                            id: preValue.id,
                            loginAccount: values.account,
                            masterAccount: values.account,
                            adjunctDeptIds: curValue,
                          }
                        }
                      }

                      break
                    }
                    case 'password':
                      if (item.value !== '') {
                        params[item.name] = item.value
                      }
                      break
                    case 'repassword':
                      if (item.value !== '') {
                        params[item.name] = item.value
                      }
                      break
                    case 'classified':
                      params[item.name] = item.value
                      // 密级，安全管理员可编辑
                      if (this.isSecAdmin) {
                        params.props.classified = item.value
                      }
                      break
                    default:
                      params[item.name] = item.value
                  }
                })
              } else {
                // 安全管理员设置密级和账号状态
                params = {
                  ...this.preResponseData,
                }
                params.statusName = values.statusName
                params.classified = values.classified
                params.props.classified = values.classified
              }
              if (params.authorizedGroupArr) {
                params.authorizedGroupNames = JSON.parse(params.authorizedGroupArr)
                  .map((item) => item.name)
                  .join()
                params.props.authorizedGroups = JSON.parse(params.authorizedGroupArr)
                  .map((item) => item.code)
                  .join()
                delete params.authorizedGroupArr
              }
              if (params.authorizedRoleArr) {
                params.authorizedRoleNames = JSON.parse(params.authorizedRoleArr)
                  .map((item) => item.name)
                  .join()
                params.props.authorizedRoles = JSON.parse(params.authorizedRoleArr)
                  .map((item) => item.code)
                  .join()
                delete params.authorizedRoleArr
              }

              let p, action
              // 批量修改，只能修改部门、职务、帐号状态、是否展示
              if (this.isBatch) {
                Object.keys(params).forEach((key) => {
                  if (!this.batchFields.includes(key)) {
                    delete params[key]
                  }
                })
                action = '批量修改'
                p = OrgService.batchUpdateOrgUser({ user: params, ids })
              } else {
                if (this.unid) {
                  params.id = this.unid
                  action = '保存'
                  p = OrgService.saveOrgUser(params)
                  // p.then((res) => {
                  //   if (params.password && params.password !== '') {
                  //     axios({
                  //       method: 'get',
                  //       url:
                  //         'api/xcoa-mobile/v1/spic-user/updateUserLoginMustChangePassword?id=' +
                  //         params.id,
                  //     })
                  //   }
                  //   resolve(res)
                  // })
                } else {
                  params.status = 1
                  action = '新建'
                  p = OrgService.createOrgUser(params)
                }
              }
              return p.then((res) => {
                if (res.status === 200) {
                  message.success(action + '成功')
                  saveFlag = true
                } else {
                  message.error(res.data?.message || action + '失败')
                }
              })
            }
          })
          .finally(() => {
            resolve(saveFlag)
          })
      })
    },
    changeParentId(oNode) {
      if (oNode[0]) {
        this.$refs.form.setFieldValue('parentId', [parseInt(oNode[0].key, 10)])
      } else {
        this.$refs.form.setFieldValue('parentId', [])
      }
    },
    changeValuePick(values, sField) {
      this.$refs.form.setFieldValue(
        sField,
        values.map((item) => {
          return {
            key: item.key,
            title: item.title,
            code: item.originalNode.props.code,
          }
        })
      )
    },
    onLoadTreeData(parentCatId, parentCatObj) {
      return new Promise((resolve) => {
        if (parentCatId) {
          return OrgService.getOrgDepTree({ id: parentCatId }).then((deps) => {
            resolve(this.parseTreeData(deps.data))
          })
        } else {
          return OrgService.getOrgDepRoot().then((roots) => {
            resolve(this.parseTreeData(roots.data))
          })
        }
      })
    },
    parseTreeData(deps) {
      return deps.map((dep) => {
        return {
          key: dep.id,
          title: dep?.props?.hierarchical === 'true' ? dep.text + '(已开启分级)' : dep.text,
          name: dep.text,
          isLeaf: dep.leaf,
          scopedSlots: {
            title: 'title',
          },
          originalNode: {
            ...dep,
          },
        }
      })
    },
  },
}
</script>

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

.warp {
  .form {
    :global(.ant-form-item-label:not(.sd-readonly)) {
      padding-bottom: 0;
      margin-bottom: 0;
    }
    :global(.ant-form-item) {
      padding-bottom: 0;
      margin-bottom: 0;
    }
  }
  .auth-roles {
    display: block;
    max-height: 86px;
    margin-top: 8px;
    overflow-y: auto;
    line-height: 1.5;
  }
  .operation-wrapper {
    width: 100%;
    overflow: hidden;
    :global(.ant-space) {
      float: right;
    }
  }
}
</style>
