<template>
  <h-row :gutter="24">
    <h-col :span="24">
      <div class="red-line"></div>
      <div class="title">
        {{ t('tenant.tenantManagement.checkOrCreateOrEditTenant.baseTitle') }}
      </div>
      <h-form
        :layout="hFormGlobalConfig.layout"
        :labelCol="hFormGlobalConfig.labelCol"
        ref="formRef"
        class="base-form"
      >
        <h-row :gutter="40">
          <h-col :span="12">
            <h-form-item
              :label="t('tenant.tenantManagement.checkOrCreateOrEditTenant.tenantName')"
              v-bind="formValidate.validateInfos.ENAME"
            >
              <h-input
                autocomplete="off"
                :placeholder="
                  t('tenant.tenantManagement.checkOrCreateOrEditTenant.namePlaceHolder')
                "
                v-model:value="formState.ENAME"
              ></h-input>
            </h-form-item>
          </h-col>
          <h-col :span="12">
            <h-form-item
              :label="t('tenant.tenantManagement.checkOrCreateOrEditTenant.tenantNum')"
              v-bind="formValidate.validateInfos.ECODE"
            >
              <h-input
                :disabled="true"
                :placeholder="
                  t('tenant.tenantManagement.checkOrCreateOrEditTenant.encoderPlaceHolder')
                "
                autocomplete="off"
                v-model:value="formState.ECODE"
              ></h-input>
            </h-form-item>
          </h-col>
          <h-col :span="12">
            <h-form-item
              :label="t('tenant.tenantManagement.checkOrCreateOrEditTenant.contacts')"
              v-bind="formValidate.validateInfos.SYSTEMUSERID"
            >
              <h-input
                autocomplete="off"
                :placeholder="
                  t('tenant.tenantManagement.checkOrCreateOrEditTenant.contactsPlaceHolder')
                "
                v-model:value="formState.SYSTEMUSERID"
              ></h-input>
            </h-form-item>
          </h-col>
          <h-col :span="12">
            <h-form-item
              :label="t('tenant.tenantManagement.checkOrCreateOrEditTenant.userCap')"
              v-bind="formValidate.validateInfos.MAXUSERCOUNT"
            >
              <h-input
                :placeholder="
                  t('tenant.tenantManagement.checkOrCreateOrEditTenant.useCapPlaceHolder')
                "
                v-model:value="formState.MAXUSERCOUNT"
              ></h-input>
            </h-form-item>
          </h-col>
          <h-col :span="12">
            <h-form-item
              :label="t('tenant.tenantManagement.checkOrCreateOrEditTenant.phone')"
              v-bind="formValidate.validateInfos.PHONECODE"
            >
              <h-input
                autocomplete="off"
                :placeholder="
                  t('tenant.tenantManagement.checkOrCreateOrEditTenant.phonePlaceHolder')
                "
                v-model:value="formState.PHONECODE"
              ></h-input>
            </h-form-item>
          </h-col>
        </h-row>
      </h-form>
    </h-col>
  </h-row>
  <h-divider class="tcl-edit-renant-divider" />
  <h-row :gutter="24">
    <h-col :span="24">
      <div class="red-line"></div>
      <div class="title">
        {{ t('tenant.tenantManagement.checkOrCreateOrEditTenant.manageTitle') }}
      </div>
      <h-row :gutter="24" class="create-renant-admin-useinfo-title">
        <h-col :span="2">
          <span>{{ t('tenant.tenantManagement.checkOrCreateOrEditTenant.eid') }}</span>
        </h-col>
        <h-col :span="9">
          <span>{{ t('tenant.tenantManagement.checkOrCreateOrEditTenant.username') }}</span>
        </h-col>
        <h-col :span="9">
          <span>{{ t('tenant.tenantManagement.checkOrCreateOrEditTenant.password') }}</span>
        </h-col>
        <h-col :span="4" style="text-align: right; padding-right: 30px">
          <span>{{ t('tenant.common.operate') }}</span>
        </h-col>
      </h-row>
      <h-form ref="formManageRef" name="dynamic_form_nest_item" :model="dynamicValidateForm">
        <h-row
          :gutter="24"
          v-for="(user, index) in dynamicValidateForm.users"
          :key="index"
          class="create-renant-admin-useinfo-row"
        >
          <h-col :span="2">
            {{ index + 1 }}
          </h-col>
          <h-col :span="9">
            <h-form-item
              :name="['users', index, 'username']"
              :rules="{
                required: true,
                pattern: /^[A-Za-z0-9]{0,100}$/,
                message: t('tenant.tenantManagement.checkOrCreateOrEditTenant.usernameRule'),
                trigger: 'blur',
              }"
            >
              <h-input
                autocomplete="off"
                v-model:value="user.username"
                :placeholder="
                  t('tenant.tenantManagement.checkOrCreateOrEditTenant.usernamePlaceHolder')
                "
              />
            </h-form-item>
          </h-col>
          <h-col :span="9">
            <h-form-item
              :name="['users', index, 'password']"
              :rules="{
                required: true,
                pattern: /^[A-Za-z0-9]{1,50}$|^\*{6}$/,
                message: t('tenant.tenantManagement.checkOrCreateOrEditTenant.passwordRule'),
                trigger: 'blur',
              }"
            >
              <h-input-search
                v-model:value="user.password"
                :placeholder="
                  t('tenant.tenantManagement.checkOrCreateOrEditTenant.passwordPlaceHolder')
                "
                @search="randomClick(index)"
              >
                <template #enterButton>
                  <!-- 随机密码按钮 插槽传入 -->
                  <h-tooltip
                    placement="top"
                    :title="t('tenant.tenantManagement.checkOrCreateOrEditTenant.randomPass')"
                  >
                    <img src="../iconImg/random2x.png" alt="" class="random-password-button" />
                  </h-tooltip>
                </template>
              </h-input-search>
            </h-form-item>
          </h-col>
          <h-col :span="4">
            <h-form-item>
              <h-button
                type="link"
                :style="hiddenDelete"
                @click="removeUser(index)"
                class="create-renant-delete-btn"
              >
                {{ t('tenant.common.delete') }}
              </h-button>
            </h-form-item>
          </h-col>
        </h-row>
        <h-divider />
        <h-form-item>
          <h-button type="dashed" block @click="addUser">
            <plus-outlined />
            {{ t('tenant.tenantManagement.checkOrCreateOrEditTenant.addUser') }}
          </h-button>
        </h-form-item>
      </h-form>
    </h-col>
  </h-row>
  <!-- <h-row
    style="
      border-top: 1px solid #e8e8e8;
      padding-top: 10px;
      margin-left: -24px;
      margin-right: -24px;
    "
  >
    <h-col :span="24" style="text-align: right; padding-right: 24px">
      <h-button style="margin: 0 20px" @click="cancelClick">
        {{ t('tenant.common.cancel') }}
      </h-button>
      <h-button type="primary" :loading="btnLoading" @click.prevent="okClick">
        {{ t('tenant.common.ok') }}
      </h-button>
    </h-col>
  </h-row> -->
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { Form, HModal } from '@crami/ui';
import { useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';
import { hFormGlobalConfig } from '@/settings/config';

interface FormState {
  ENAME: string;
  ECODE: string;
  SYSTEMUSERID: string;
  MAXUSERCOUNT: string;
  PHONECODE: string;
}
interface User {
  username: string;
  password: string;
  eid: string;
}

/**控件对外数据*/
const formProps = {
  componentProps: {
    type: Object,
  },
};
const useForm = Form.useForm;
export default defineComponent({
  name: 'EditRenant',
  props: formProps,
  components: {
    PlusOutlined,
  },
  setup: (props, { emit }) => {
    const { t } = useI18n();
    const initEid = props.componentProps.params.getDataParams.ObjectID || '';
    const formManageRef = ref();
    const formCtrl = ref();
    let tenantEid = '';
    const deleteData: string[] = [];
    const formRef = ref();
    const btnLoading = ref(false);
    const dynamicValidateForm = reactive<{ users: User[] }>({
      users: [
        {
          username: '',
          password: '',
          eid: '',
        },
      ],
    });

    const hiddenDelete = computed(() => {
      return { display: dynamicValidateForm.users.length <= 1 ? 'none' : 'block' };
    });

    const formState = reactive<FormState>({
      ENAME: '',
      ECODE: '',
      SYSTEMUSERID: '',
      MAXUSERCOUNT: '',
      PHONECODE: '',
    });
    const formRules = reactive({
      ENAME: [
        {
          required: true,
          message: t('tenant.tenantManagement.checkOrCreateOrEditTenant.enameRule'),
          pattern: /^[\s\S]{0,20}$/,
          trigger: 'change',
        },
      ],
      ECODE: [
        {
          required: true,
          pattern: /^[A-Za-z0-9]{0,20}$/,
          message: t('tenant.tenantManagement.checkOrCreateOrEditTenant.ecodeRuleC'),
          trigger: 'change',
        },
      ],
      SYSTEMUSERID: [
        {
          pattern: /^([\s\S]{0,20})?$/,
          message: t('tenant.tenantManagement.checkOrCreateOrEditTenant.enameRule'),
          trigger: 'change',
        },
      ],
      MAXUSERCOUNT: [
        {
          required: true,
          pattern: /^[0-9]{0,5}$/,
          message: t('tenant.tenantManagement.checkOrCreateOrEditTenant.maxusercountRule'),
          trigger: 'change',
        },
      ],
      PHONECODE: [
        {
          pattern: /^0?(13|14|15|16|17|18|19)[0-9]{9}$/,
          message: t('tenant.tenantManagement.checkOrCreateOrEditTenant.phoneRule'),
          trigger: 'change',
        },
      ],
    });

    const formValidate = useForm(formState, formRules);

    const randomClick = (index: number) => {
      dynamicValidateForm.users[index].password = getRandomPassword();
    };

    const getRandomPassword = () => {
      let new_pwd = '';
      let j = 0;
      let char = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
      for (let i = 0; i < 6; i++) {
        j = Math.floor(Math.random() * char.length);
        new_pwd += char.charAt(j);
      }
      return new_pwd;
    };

    const removeUser = (index: number) => {
      if (dynamicValidateForm.users.length == 1) {
        return;
      }
      const items = dynamicValidateForm.users.splice(index, 1);
      items.length > 0 && items[0].eid.length > 0 && deleteData.push(items[0].eid);
    };
    const addUser = () => {
      if (dynamicValidateForm.users.length > 4) {
        message.warning({
          content: t('tenant.tenantManagement.checkOrCreateOrEditTenant.addUserWarn'),
        });
        return;
      }
      dynamicValidateForm.users.push({
        username: '',
        password: '',
        eid: '',
      });
    };

    const cancel = () => {
      // HModal.destroyAll();
      emit('end', null);
    };

    const ok = () => {
      formValidate
        .validate()
        .then((res: any) => {
          formManageRef.value.validate().then((mRes: any) => {
            const result = {
              tenantData: { ...res, EID: tenantEid },
            };
            const manageArr: any[] = [];
            const users = dynamicValidateForm.users;
            for (let i = 0; i < users.length; i++) {
              const item = users[i];
              const itemParam = { USER_NAME: item.username, USER_PWD: item.password };
              if (item.eid.length > 0) {
                itemParam['EID'] = item.eid;
              }
              manageArr.push(itemParam);
            }
            //判断manageArr中的每个对象的USER_NAME 不重复
            const data = [];
            manageArr.forEach(item => {
              data.push(item.USER_NAME);
            });
            if (new Set(data).size != data.length) {
              message.warning({
                content: t('tenant.tenantManagement.checkOrCreateOrEditTenant.manageRepeatMsg'),
              });
              return;
            } else {
              result['userData'] = manageArr;
              result['eidstr'] = deleteData;
              submitEvent(result);
            }
          });
        })
        .catch((err: any) => {
          //校验失败，返回校验信息，字段数据
          console.info(err);
        });
    };

    const submitEvent = async (params: any) => {
      btnLoading.value = true;
      const data = await useHttp({
        url: '/api/system/tenant/save',
        method: 'post',
        params: params,
      });
      btnLoading.value = false;
      if (data.code == 200) {
        emit('end', { success: true, code: 200, msg: data.msg });
        message.success(data.msg);
      } else {
        message.error(data.msg);
      }
    };

    const getUserInfo = async () => {
      const result = await useHttp({
        url: '/api/system/tenant/getOneInfo',
        method: 'post',
        params: {
          EID: initEid,
        },
      });
      const userData = result.data.data['userData'];
      const tenantData = result.data.data['tenantData'];
      tenantEid = tenantData['EID'];
      Object.assign(formState, tenantData);
      if (userData.length > 0) {
        dynamicValidateForm.users.length = 0;
        for (let i = 0; i < userData.length; i++) {
          const item = userData[i];
          const user = {
            username: item.USER_NAME,
            password: '******',
            eid: item.EID,
          };
          dynamicValidateForm.users.push(user);
        }
      }
    };

    onMounted(() => {
      getUserInfo();
    });

    return {
      t,
      formCtrl,
      formValidate,
      formState,
      formManageRef,
      hiddenDelete,
      btnLoading,

      cancel,
      ok,
      randomClick,

      formRef,
      dynamicValidateForm,
      removeUser,
      addUser,
      hFormGlobalConfig,
    };
  },
});
</script>

<style lang="less" scoped>
@import '@/theme/default/variables.less';

.title {
  font-size: 16px;
  font-weight: bold;
  color: black;
  margin-bottom: 10px;
}
:deep(.base-form) {
  margin-top: 15px;
  margin-bottom: 10px;
}
.button-box {
  position: relative;
  height: 35px;
}
.manage-container {
  margin-top: 15px;
  margin-bottom: 40px;
  .manage-box {
    display: flex;
    // justify-content: center;
    margin-bottom: 10px;
    label {
      &:before {
        display: inline-block;
        margin-right: 4px;
        font-size: 14px;
        font-family: SimSun, sans-serif;
        line-height: 1;
        content: '*';
        color: #fa5555;
        font-weight: 500;
      }
    }
    .manage-name {
      display: flex;
      align-items: center;
      .manage-input {
        width: 60%;
      }
    }
    .manage-password {
      display: flex;
      align-items: center;
      .manage-input {
        width: 70%;
      }
    }
    .manage-button {
      display: flex;
      align-items: center;
      width: 135px;
      // background-color: red;
      .manage-delete {
        margin-right: 10px;
      }
    }
  }
}
.tcl-create-renant-divider {
  margin-top: 0;
}
//标题前方红杠样式
.red-line {
  width: 4px;
  height: 12px;
  background: @modal-formgroup-color;
  // background: linear-gradient(180deg, #f55448 0%, #ff8076 100%);
  float: left;
  margin-top: 7px;
  margin-right: 7px;
}
// 删除按钮
.create-renant-delete-btn {
  border: none;
  float: right;
}
//弹窗下边距
.ant-modal-confirm-content {
  padding-bottom: 10px !important;
}
//随机密码按钮样式
.ant-btn.ant-btn-primary.ant-input-search-button {
  img {
    width: 14px;
    height: 14px;
    margin: auto;
  }
}
// 管理员信息行间样式
.create-renant-admin-useinfo-title {
  color: rgba(51, 51, 51, 1);
  font-weight: bold;
  background: #f5f6f7;
  height: 36px;
  line-height: 35px;
  font-size: 14px;
  margin-left: 0px !important;
  margin-right: 0px !important;
  .ant-col.ant-col-2 {
    padding-left: 20px !important;
    padding-right: 20px !important;
  }
  .ant-col.ant-col-4 {
    padding-left: 20px !important;
    padding-right: 20px !important;
  }
  .ant-col:nth-child(2) {
    padding-left: 30px !important;
  }
  .ant-col:nth-child(3) {
    padding-left: 20px !important;
  }
}
.ant-row.create-renant-admin-useinfo-row {
  display: flex;
  align-items: center;
  margin-left: 0 !important;
  margin-right: 0 !important;
  padding-left: 20px !important;
  padding-right: 20px !important;
  height: 80px;
  .ant-row.ant-form-item {
    margin-bottom: 0px;
  }
  :deep(.ant-row.ant-form-item.ant-form-item-has-error) {
    .ant-col.ant-form-item-control {
      .ant-form-item-explain.ant-form-item-explain-connected {
        margin-bottom: 0px !important;
      }
    }
  }
  .ant-col.ant-col-2 {
    padding-left: 0px !important;
    padding-right: 0px !important;
  }
  .ant-btn.ant-btn-link.create-renant-delete-btn.h-btn-icon.create-renant-delete-btn {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  .ant-col.ant-col-4 {
    padding-left: 20 !important;
    padding-right: 20 !important;
  }
}
.create-renant-admin-useinfo-row {
  height: 52px;
  line-height: 20px;

  .ant-col {
    margin-top: 10px;
  }
}
// 分割线样式
.ant-divider.ant-divider-horizontal {
  margin-top: 10px;
  margin-bottom: 24px;
}
//弹窗中输入框高度
// .base-form {
//   input {
//     height: 40px;
//   }
// }
</style>
