<template>
  <div :class="$style.warp">
    <sd-form ref="form" :key="updateKey" :init-values="values">
      <template v-slot="{ model }">
        <table>
          <colgroup>
            <col width="15%" />
            <col width="35%" />
            <col width="15%" />
            <col width="35%" />
          </colgroup>
          <tr v-for="row in Math.ceil(values.length / columnNum)" :key="row">
            <sd-form-item-td v-for="item in valuesMap[row - 1]" :key="item" :name="item">
              <template v-if="item === 'complexity'" v-slot:read-and-edit>
                <sd-select v-model="model.complexity" :options="options" mode="multiple" />
              </template>
            </sd-form-item-td>
          </tr>
        </table>
      </template>
    </sd-form>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-classify-import'

export default {
  name: 'SdOrgClassify',
  metaInfo: {
    title: 'SdOrgClassify',
  },
  components,
  props: {
    unid: {
      type: String,
      default: function() {
        return null
      },
    },
  },
  data() {
    return {
      options: [
        {
          id: '1',
          name: '含大写字母',
        },
        {
          id: '2',
          name: '含小写字母',
        },
        {
          id: '3',
          name: '含数字',
        },
        {
          id: '4',
          name: '含特殊字符',
        },
      ],
      columnNum: 2,
      updateKey: 0,
      listDataUrl: 'api/framework/v1/usergroup-manager/userGroup/users/' + this.unid,
      values: [
        {
          caption: '编码',
          name: 'value',
          dataType: 'string',
          required: true,
        },
        {
          caption: '密码最少长度',
          name: 'minLength',
          dataType: 'number',
          required: true,
          attr: {
            decimalPrecision: '0',
            minValue: 0,
          },
        },
        {
          caption: '密级',
          name: 'name',
          dataType: 'string',
          required: true,
        },
        {
          caption: '密码复杂度',
          name: 'complexity',
          dataType: 'string',
          attr: {
            selectListItem: [
              {
                value: '1',
                label: '含大写字母',
              },
              {
                value: '2',
                label: '含小写字母',
              },
              {
                value: '3',
                label: '含数字',
              },
              {
                value: '4',
                label: '含特殊字符',
              },
            ],
          },
        },
        {
          caption: '密码有效期（天）',
          name: 'periodOfValidity',
          dataType: 'number',
          required: true,
          attr: {
            decimalPrecision: '0',
            minValue: 0,
          },
        },

        {
          caption: '密码尝试次数',
          name: 'maxAllowAttempts',
          dataType: 'number',
          required: true,
          attr: {
            decimalPrecision: '0',
            minValue: 0,
          },
        },
        {
          caption: '锁定时长（分钟）',
          name: 'autoUnlockTime',
          dataType: 'number',
          required: true,
          attr: {
            decimalPrecision: '0',
            minValue: 0,
          },
        },
        {
          caption: '登录失败预警设置',
          name: 'warnAttempts',
          dataType: 'number',
          required: true,
          attr: {
            decimalPrecision: '0',
            minValue: 0,
          },
        },
        {
          caption: '首次登录改密码',
          name: 'firstLoginChangePwd',
          required: true,
          dataType: 'selectlist',
          attr: {
            defaultValue: '0',
            selectListItem: [
              {
                value: '1',
                label: '是',
              },
              {
                value: '0',
                label: '否',
              },
            ],
          },
        },
      ],
      loadingMsg: null,
    }
  },
  computed: {
    valuesMap() {
      const values = []
      const srcValues = this.values
      const columnNum = this.columnNum

      srcValues.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
    },
  },
  watch: {
    unid: {
      handler(newVal, oldVal) {
        this.getDefaultValue()
      },
      immediate: true,
    },
  },
  methods: {
    getDefaultValue() {
      if (this.unid) {
        OrgService.classify.getDoc({ id: this.unid }).then((res) => {
          const data = res.data
          this.values.forEach((item) => {
            if (['complexity', 'firstLoginChangePwd'].indexOf(item.name) > -1) {
            } else {
              this.$refs.form.setFieldValue(item.name, data[item.name])
            }
          })
          if (data.firstLoginChangePwd === true) {
            this.$refs.form.setFieldValue('firstLoginChangePwd', '1')
          } else {
            this.$refs.form.setFieldValue('firstLoginChangePwd', '0')
          }

          const complexity = []
          if (data.complexity.indexOf('(?=.*[A-Z])') > -1) {
            complexity.push({
              id: '1',
              name: '含大写字母',
            })
          }
          if (data.complexity.indexOf('(?=.*[a-z])') > -1) {
            complexity.push({
              id: '2',
              name: '含小写字母',
            })
          }
          if (data.complexity.indexOf('(?=.*[0-9])') > -1) {
            complexity.push({
              id: '3',
              name: '含数字',
            })
          }
          if (data.complexity.indexOf('(?=.*[^a-zA-Z0-9])') > -1) {
            complexity.push({
              id: '4',
              name: '含特殊字符',
            })
          }

          this.$refs.form.setFieldValue('complexity', complexity)
        })
      } else {
        Promise.all([]).then(() => {
          this.values.forEach((item) => {
            if (['complexity', 'firstLoginChangePwd'].indexOf(item.name) > -1) {
            } else {
              this.$refs.form.setFieldValue(item.name, undefined)
            }
          })

          this.$refs.form.setFieldValue('firstLoginChangePwd', '0')

          this.$refs.form.setFieldValue('complexity', [])
        })
      }
    },
    save() {
      return new Promise((resolve) => {
        this.$refs.form.validateFields().then((success) => {
          if (success) {
            const params = {}

            const values = this.$refs.form.getFieldsValue()

            this.$refs.form.getBackendValues().forEach((item) => {
              params[item.name] = item.value

              if (item.name === 'firstLoginChangePwd') params[item.name] = item.value === '1'
              if (item.name === 'complexity') {
                if (item.value) {
                  params[item.name] = JSON.parse(item.value)
                    .map((complexity) => {
                      return complexity.id === '1'
                        ? '(?=.*[A-Z])'
                        : complexity.id === '2'
                        ? '(?=.*[a-z])'
                        : complexity.id === '3'
                        ? '(?=.*[0-9])'
                        : complexity.id === '4'
                        ? '(?=.*[^a-zA-Z0-9])'
                        : ''
                    })
                    .join(',')
                  if (params[item.name] !== '') {
                    params[item.name] = params[item.name] + '.{' + values.minLength + ',30}'
                  }
                } else {
                  params[item.name] = ''
                }
              }
            })

            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })
            if (this.unid) {
              params.id = this.unid
              return OrgService.classify
                .saveDoc(params)
                .then((res) => {
                  if (res.status === 200) {
                    message.success('保存成功')
                    resolve(true)
                  } else {
                    message.error(res.data?.message || '保存失败')
                  }
                })
                .catch((res) => {
                  message.error(res?.response?.data?.message || '保存失败')
                })
                .finally(() => {
                  this.loadingMsg?.()
                })
            } else {
              params.id = -1
              return OrgService.classify
                .saveDoc(params)
                .then((res) => {
                  if (res.status === 200) {
                    message.success('新建成功')
                    resolve(true)
                  } else {
                    message.error(res.data?.message || '新建失败')
                  }
                })
                .catch((res) => {
                  message.error(res?.response?.data?.message || '新建失败')
                })
                .finally(() => {
                  this.loadingMsg?.()
                })
            }
          }
        })
      })
    },
  },
}
</script>

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