<template>
  <el-dialog title="添加账号" :visible.sync="dialogStatus" width="800px" @close="dialogClose" @open="dialogOpen" class="enterprise-add-account"
    custom-class="enterprise-add-account-dialog" :close-on-click-modal="false">
    <div class="enterprise-add-account-inner">
      <el-form :model="accountForm" ref="accountForm" :rules="rules">
        <transition-group tag="div" class="enterprise-add-account-list" name="list" appear>
          <div class="enterprise-add-account-item" v-for="(item,index) of accountForm.accountList" :key="item.uid">
            <div class="account-nickname">
              <el-form-item label="用户名称" :prop="`accountList[${index}].nickName`" :rules="rules.nickName">
                <el-input v-model="accountForm.accountList[index].nickName" placeholder="请输入用户名称" size="normal" clearable></el-input>
              </el-form-item>
            </div>
            <div class="account-phone">
              <el-form-item label="手机号码" :prop="`accountList[${index}].phonenumber`" :rules="rules.phonenumber">
                <el-input v-model="accountForm.accountList[index].phonenumber" placeholder="请输入手机号码" size="normal" clearable></el-input>
              </el-form-item>
            </div>
            <div class="remove-account-item" @click="removeAccount(item.uid)" v-if="accountForm.accountList.length > 1"><i class="el-icon-delete"></i>
            </div>
          </div>
        </transition-group>
        <!-- 添加按钮 -->
        <div class="add-account-btn" @click="addAccount">
          <i class="el-icon-plus"></i>
          <span>增加账号</span>
        </div>
      </el-form>
    </div>
    <template slot="footer">
      <!-- 底部提交 取消按钮 -->
      <div class="add-account-footer">
        <el-button type="primary" size="medium" @click="submitAdd">确定</el-button>
        <el-button size="medium" @click="dialogStatus = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script>
import { Loading } from 'element-ui';
import { enterpriseAddAccountApi } from "@/api/enterpriseManagement/enterpriseManagement";
import { phoneNumberValidator, requiredStrLengthValidator } from "@/utils/validate";
import { elementMessageSingleton, hasDuplicates } from "@/utils/";
import { v4 } from 'uuid';
export default {
  name: "enterpriseAddAccount",
  props: {
    openStatus: {
      type: Boolean,
      default: false
    },
    enterpriseInfo: {
      type: Object,
      default: () => ({})
    },
    addAccountCount: {
      type: [String, Number],
      default: 1
    }
  },
  watch: {
    openStatus(newValue) {
      this.dialogStatus = newValue;
    },
    addAccountCount(newValue) {
      this.comAddAccountCount = newValue;
    },
    enterpriseInfo: {
      handler(newValue) {
        this.comEnterpriseInfo = newValue;
      },
      deep: true
    }
  },
  data() {
    return {
      dialogStatus: this.openStatus,
      comEnterpriseInfo: this.enterpriseInfo,
      comAddAccountCount: this.addAccountCount,
      accountForm: {
        accountList: []
      },
      rules: {
        nickName: [{ required: true, trigger: ["blur"], validator: requiredStrLengthValidator("用户名称") }],
        phonenumber: [{ required: true, trigger: ["blur", "change"], validator: phoneNumberValidator }]
      }
    };
  },
  //可访问data属性
  created() {

  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    dialogOpen() {
      this.addAccount();
    },
    dialogClose() {
      this.accountForm = this.$options.data.call(this).accountForm;
      this.$emit("dialogClose");
    },
    removeAccount(uid) {
      const index = this.accountForm.accountList.findIndex(item => item.uid == uid);
      if (index > -1) {
        this.accountForm.accountList.splice(index, 1);
      }
    },
    addAccount() {
      if (this.comAddAccountCount >= 6) return elementMessageSingleton("warning", "该租户下已经添加了五个账号");
      if (this.accountForm.accountList?.length >= 5) return elementMessageSingleton("warning", "最多添加五个账号");
      const remaining = 6 - this.comAddAccountCount;
      const len = this.accountForm?.accountList?.length;
      if (len >= remaining) return elementMessageSingleton("warning", `该租户下剩余可添加账号个数为 ${remaining} 个,现已添加 ${len} 个`);
      this.accountForm.accountList.push({
        nickName: "",
        phonenumber: "",
        uid: v4()
      });
    },
    submitAdd() {
      this.$refs["accountForm"].validate(async flag => {
        if (!flag) return;
        const { hasRepeat, repeatKey } = hasDuplicates(JSON.parse(JSON.stringify(this.accountForm.accountList)), "phonenumber");
        if (hasRepeat) return elementMessageSingleton("warning", `电话号码 ${repeatKey} 不允许重复创建`);
        const loadingService = Loading.service({
          target: ".enterprise-add-account-dialog",
          lock: true,
          text: "正在添加账号,请勿关闭窗口"
        });
        let successCount = 0;
        try {
          // 验证通过提交信息
          const array = (JSON.parse(JSON.stringify(this.accountForm.accountList))).map(({ nickName, phonenumber }) => ({ nickName, phonenumber }));
          let len = array.length;
          let count = 0;
          while (count < len) {
            try {
              const result = await enterpriseAddAccountApi({
                tenantId: this.comEnterpriseInfo.tenantId,
                packageId: this.comEnterpriseInfo.packageId,
                nickName: array[count].nickName,
                phonenumber: array[count].phonenumber,
              });
              if (result.code == 200) {
                successCount++;
                // 进度加载
              } else {
                elementMessageSingleton("error", result.msg);
              }
            } catch (error) {
              console.log(error);
            } finally {
              count++;
            }
          }
          this.dialogStatus = false;
        } catch (error) {
          console.log(error);
        } finally {
          loadingService.close();
          successCount > 0 ? this.$message.success("添加账号成功") : null;
        }
      });
    }
  },
}
</script>
<style lang="scss" scoped>
.enterprise-add-account {
  ::v-deep .enterprise-add-account-dialog {
    .el-dialog__header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 20px;
      border-bottom: 1px solid #eee;
      box-sizing: border-box;

      .el-dialog__title {
        font-size: 16px;
      }

      .el-dialog__headerbtn {
        position: static;
        display: flex;
        align-items: center;
      }
    }

    .el-dialog__body {
      padding: 20px;
      box-sizing: border-box;

      .enterprise-add-account-inner {
        .el-form {
          display: flex;
          justify-content: space-between;
          .enterprise-add-account-list {
            display: flex;
            flex-direction: column;
            position: relative;

            & > .enterprise-add-account-item:first-of-type {
              margin-top: 0px;
            }

            .enterprise-add-account-item {
              display: flex;
              align-items: center;
              margin-top: 15px;

              &:hover {
                .remove-account-item {
                  opacity: 1;
                  & > i {
                    cursor: pointer;
                  }
                }
              }

              .account-phone {
                margin-left: 30px;
              }

              .el-form-item {
                display: flex;
                margin-bottom: 0px;

                .el-form-item__content,
                .el-form-item__label {
                  line-height: 32px;
                }

                .el-input {
                  .el-input__inner {
                    line-height: 32px;
                    height: 32px;

                    &::placeholder {
                      color: #c0c4cc !important;
                      font-weight: 400 !important;
                      font-size: 12px;
                    }
                  }

                  .el-input__suffix {
                    display: flex;
                    align-items: center;

                    .el-input__icon {
                      line-height: 32px;
                    }
                  }
                }

                .el-form-item__error {
                  padding-top: 2px;
                }
              }

              .remove-account-item {
                display: flex;
                align-items: center;
                margin-left: 15px;
                opacity: 0;
                transition: opacity 0.3s;
                & > i {
                  font-size: 16px;

                  &:hover {
                    color: #f56c6c;
                  }
                }
              }
            }
          }
          .add-account-btn {
            line-height: 32px;
            align-self: flex-start;
            cursor: pointer;
            color: #1890ff;
            font-size: 14px;

            span {
              margin-left: 5px;
            }
          }
        }
      }
    }

    .el-dialog__footer {
      padding: 0px;
      .add-account-footer {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding: 20px;
        border-top: 1px solid #eee;
        box-sizing: border-box;

        .el-button {
          height: 32px;
          line-height: 32px;
          padding: 0px 20px;
          box-sizing: border-box;
        }
      }
    }
  }
}
</style>
