<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="10vh"
    width="750px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :size="'mini'"
            :rules="rulesThis"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item
                  v-if="id === 'add' || isDetail"
                  label="账号"
                  prop="username"
                >
                  <el-input
                    v-model="ruleForm.username"
                    maxlength="100"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="真实姓名" prop="name">
                  <el-input
                    v-model="ruleForm.name"
                    :placeholder="'真实姓名'"
                    :disabled="isDetail"
                    maxlength="100"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="mobile">
                  <el-input
                    v-model="ruleForm.mobile"
                    :placeholder="'手机号'"
                    maxlength="11"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所在部门" prop="itemid">
                  <all-organize
                    :value="ruleForm.itemid"
                    :is-detail="isDetail"
                    :disabled="isDetail"
                    :multiple="true"
                    :size="'mini'"
                    :checkStrictly="true"
                    :placeholder="'所在部门'"
                    @searchChange="itemidChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="ruleForm.email"
                    :placeholder="'邮箱'"
                    maxlength="100"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="角色" prop="role_id">
                  <el-radio-group
                    v-model="ruleForm.role_id"
                    :size="'mini'"
                    :disabled="isDetail"
                  >
                    <el-radio
                      v-for="item in roleList"
                      :key="item.id"
                      :label="item.id"
                      :disabled="item.status !== '1'"
                      >{{ item.role_name }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="业务公司" prop="companyArr">
                  <el-row>
                    <el-col :span="20">
                      <el-checkbox
                        :size="'mini'"
                        :indeterminate="isIndeterminate"
                        v-model="ruleForm.is_all"
                        @change="handleCheckAllChange"
                        >全选</el-checkbox
                      >
                      <el-checkbox-group
                        :size="'mini'"
                        v-model="ruleForm.companyArr"
                        @change="handleCheckedCitiesChange"
                        class="“fl"
                      >
                        <el-checkbox
                          style="display: block; margin: 0; box-sizing: border-box"
                          v-for="(item, i) in coptions"
                          :key="item.id + i"
                          :label="item.id"
                          :disabled="item.status === '0'"
                          >{{ item.company }}</el-checkbox
                        >
                      </el-checkbox-group>
                    </el-col>
                    <el-col :span="4" style="padding: 33px 0 0 0">
                      <el-radio-group v-model="ruleForm.is_main">
                        <el-radio
                          v-for="(si, sii) in is_mainoptions"
                          :key="si.id + sii"
                          style="
                            display: block;
                            margin: 0;
                            padding: 6px 0 0 0;
                            height: 28px;
                            box-sizing: border-box;
                          "
                          :disabled="si.status === '0'"
                          :label="si.id"
                          >设为默认</el-radio
                        >
                      </el-radio-group>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="业务平台" prop="platform">
                  <el-checkbox-group
                    :size="'mini'"
                    v-model="ruleForm.platform"
                    class="“fl"
                  >
                    <el-checkbox
                      style="display: block; margin: 0; box-sizing: border-box"
                      v-for="(item, i) in platformoptions"
                      :key="item.id + i"
                      :label="item.id"
                      >{{ item.platform_name }}</el-checkbox
                    >
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="6" class="bottom-btn">
          <el-button v-if="!isDetail" type="primary" @click="submitForm" :size="'mini'"
            >保 存
          </el-button>
          <el-button @click="showModelThis = false" :size="'mini'">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/interest/account";
import resToken from "@/mixins/resToken";
import {
  isnumber,
  isMobile,
  validEmail,
  isAlphanumeric,
  isChinese,
  isEmoticon,
  validAlphabets,
} from "@/utils/validate";
export default {
  name: "Account",
  props: ["showModel", "id", "isDetail"],
  mixins: [resToken],
  data() {
    const validateusername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("账号不能为空！"));
      } else {
        if (value.length < 6 || value.length > 18) {
          callback(new Error("账号规则为6~18位数字与字母组合！"));
        } else {
          if (isnumber(value)) {
            callback(new Error("账号规则为6~18位数字与字母组合！"));
          } else if (validAlphabets(value)) {
            callback(new Error("账号规则为6~18位数字与字母组合！"));
          } else if (!isAlphanumeric(value)) {
            callback(new Error("账号规则为6~18位数字与字母组合！"));
          } else {
            callback();
          }
        }
      }
    };
    const validatename = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("真实姓名不能为空！"));
      } else {
        if (value.length < 2 || value.length > 12) {
          callback(new Error("真实姓名规则为2~12位汉字！"));
        } else {
          if (!isChinese(value)) {
            callback(new Error("真实姓名规则为2~12位汉字！"));
          } else if (isEmoticon(value)) {
            callback(new Error("真实姓名规则为2~12位汉字！"));
          } else {
            callback();
          }
        }
      }
    };
    const validatemobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空！"));
      } else {
        if (!isMobile(value)) {
          callback(new Error("手机号格式不正确！"));
        } else {
          callback();
        }
      }
    };

    const validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        if (!validEmail(value)) {
          callback(new Error("邮箱格式不正确！"));
        } else {
          callback();
        }
      }
    };
    return {
      roleList: [],
      loading: false,
      title: "添加账号",
      organizeList: [],
      showModelThis: this.showModel,
      coptions: [],
      is_mainoptions: [],
      isIndeterminate: false,
      ruleForm: {
        username: "", // 账号
        name: "", // 真实姓名
        mobile: "",
        email: "",
        role_id: "",
        is_all: "",
        status: "1",
        itemid: [],
        companyArr: [],
        is_main: "",
        platform: [],
      },
      platformoptions: [],
      rulesThis: this.rules,
      rules: {
        name: [
          {
            required: true,
            validator: validatename,
            trigger: "blur",
          },
        ],
        username: [
          {
            required: true,
            validator: validateusername,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: "blur",
          },
        ],
        email: [
          {
            required: false,
            validator: validateEmail,
            trigger: "blur",
          },
        ],
        role_id: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change",
          },
        ],
        itemid: [
          {
            type: "array",
            required: true,
            message: "请选择所在部门",
            trigger: "change",
          },
        ],

        companyArr: [
          {
            type: "array",
            required: true,
            message: "至少选择一个业务公司",
            trigger: "change",
          },
        ],

        platform: [
          {
            type: "array",
            required: true,
            message: "至少选择一个业务平台",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  mounted() {},
  methods: {
    itemidChange(e) {
      this.ruleForm.itemid = e;
      this.$refs.ruleForm.validateField("itemid");
    },
    async initForm() {
      this.loading = true;

      await this.getClist();
      await this.getRole();
      await this.getWorkList();
      await this.getTerraceList();
      if (this.id === "add") {
        await this.resetForm();
      } else {
        await this.initData();
      }
      if (this.id === "add") {
        this.title = "添加账号";
        this.rulesThis = this.rules;
      } else {
        if (this.isDetail) {
          this.title = "账号详情";
          this.rulesThis = {};
        } else {
          this.title = "修改账号";
          this.rulesThis = this.rules;
        }
      }
      this.loading = false;
    },

    async getClist() {
      this.organizeList = [];
      const { code, data, message } = await asyncRequest.getClist({
        size: 10000,
      });
      if (code === 0) {
        this.organizeList = data;
        this.recursion(this.organizeList);
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    //获取全部业务公司
    async getWorkList() {
      this.coptions = [];
      this.is_mainoptions = [];
      const { code, data, message } = await asyncRequest.getWorkList({
        size: 10000,
        page: 1,
      });
      if (code === 0) {
        const { list, count } = data;
        this.coptions = list;
        this.coptions.forEach((e) => {
          this.is_mainoptions.push({
            id: e.id,
            status: e.status,
          });
        });
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    //获取全部业务平台
    async getTerraceList() {
      this.platformoptions = [];
      const { code, data, message } = await asyncRequest.getTerraceList({
        size: 10000,
        page: 1,
        is_show: "0",
      });
      if (code === 0) {
        const { list, count } = data;
        this.platformoptions = list;
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    handleCheckAllChange(val) {
      let checkedCount = val ? this.coptions.length : 0;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.coptions.length;
      this.ruleForm.companyArr = [];
      if (checkedCount !== 0) {
        this.coptions.forEach((e) => {
          if (e.status === "1") {
            this.ruleForm.companyArr.push(e.id);
          }
        });
      }
    },
    handleCheckedCitiesChange(value) {
      console.log(value);
      let checkedCount = value.length;
      this.ruleForm.is_all = checkedCount === this.coptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.coptions.length;
    },
    recursion(list) {
      list.map((v) => {
        if (v && Array.isArray(v.child)) {
          v.value = v.id + "";
          v.label = v.name;
          if (v.child.length === 0) {
            delete v["child"];
          } else {
            this.recursion(v.child);
          }
        }
        return v;
      });
    },
    async getRole() {
      const model = {
        status: "", // 状态
        level: "", // 姓名
        role_name: "",
      };
      const res = await asyncRequest.getRole(model);
      if (res && res.code === 0 && res.data) {
        this.roleList = res.data;
        this.roleList.map((v1) => {
          v1.id += "";
          v1.status += "";
          return v1;
        });
      }
    },
    async initData() {
      const { code, data, message } = await asyncRequest.detail({
        id: this.id,
      });
      if (code === 0) {
        await this.resetForm(data);
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    async resetForm(sitem) {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          if (sitem) {
            const {
              username,
              nickname,
              mobile,
              email,
              roleid,
              status,
              depart,
              business,
              platform,
            } = sitem;
            let depart_code = [];
            if (depart && depart.length > 0) {
              depart.forEach((a) => {
                depart_code.push(a.depart_code);
              });
            }
            let copyBusiness =
              business && business.length > 0 ? JSON.parse(JSON.stringify(business)) : [];

            let businessList =
              business && business.length > 0 ? JSON.parse(JSON.stringify(business)) : [];
            businessList.forEach((a, ai) => {
              let sindex = this.coptions.findIndex((b) => b.id == a.businessid);
              if (sindex === -1) {
                copyBusiness.splice(ai, 1);
              }
            });
            let is_all = false,
              add = 0;
            // if(copyBusiness.length===)

            let resbusinesslist = [],
              is_main = "";
            if (copyBusiness && copyBusiness.length > 0) {
              copyBusiness.forEach((a) => {
                resbusinesslist.push(a.businessid);
                if (a.is_main === "1") {
                  is_main = a.businessid;
                }
              });
            }

            let copyplatform =
              platform && platform.length > 0 ? JSON.parse(JSON.stringify(platform)) : [];
            let platformList =
              platform && platform.length > 0 ? JSON.parse(JSON.stringify(platform)) : [];
            platformList.forEach((a, ai) => {
              let sindex = this.platformoptions.findIndex((b) => b.id == a.id);
              if (sindex === -1) {
                copyplatform.splice(ai, 1);
              }
            });
            let resplatformlist = [];
            if (copyplatform && copyplatform.length > 0) {
              copyplatform.forEach((a) => {
                resplatformlist.push(a.id);
              });
            }

            this.ruleForm = {
              username: username || "", // 账号
              name: nickname || "", // 真实姓名
              mobile: mobile || "",
              email: email || "",
              role_id: roleid || "",
              status: status || "",
              itemid: depart_code,
              is_main: is_main || "",
              companyArr: resbusinesslist || [],
              platform: resplatformlist || [],
              is_all: resbusinesslist.length === this.coptions.length,
            };
            this.isIndeterminate =
              resbusinesslist.length > 0 && resbusinesslist.length < this.coptions.length;
          } else {
            this.ruleForm = {
              username: "", // 账号
              name: "", // 真实姓名
              mobile: "",
              email: "",
              role_id: "",
              is_all: "",
              status: "1",
              itemid: [],
              companyArr: [],
              is_main: "",
              platform: [],
            };
            this.handleCheckAllChange();
          }
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (!this.loading) {
            this.loading = true;
            const {
              username,
              name,
              mobile,
              email,
              role_id,
              status,
              itemid,
              is_main,
              is_all,
              companyArr,
              platform,
            } = JSON.parse(JSON.stringify(this.ruleForm));
            let list = [],
              isok = true;
            companyArr.forEach((e) => {
              let item = {
                businessid: e,
                is_main: is_main === e ? "1" : "0",
              };
              list.push(item);
              let findex = this.coptions.findIndex((a) => a.id === e && a.status === "0");
              if (findex !== -1) {
                isok = false;
              }
            });
            if (!isok) {
              this.$message.warning("不能选择禁用的业务企业！");
              this.loading = true;
              return;
            }
            const model = {
              id: this.id,
              username: username || "", // 账号
              nickname: name || "", // 真实姓名
              mobile: mobile || "",
              email: email || "",
              role: role_id || "",
              status: status || "",
              itemid: itemid || [],
              is_all: is_all ? "1" : "0",
              platform: platform || [],
              companyArr: list,
            };
            let res = {};
            if (this.id === "add") {
              delete model["id"];
              res = await asyncRequest.add(model);
            } else {
              res = await asyncRequest.update(model);
            }
            this.loading = false;
            if (res && res.code === 0) {
              const title = this.id === "add" ? "添加成功" : "修改成功";
              this.$notify.success({
                title,
                message: "",
              });
              this.showModelThis = false;
              // 刷新
              this.$emit("refresh");
            } else if (res && res.code >= 100 && res.code <= 104) {
              await this.logout();
            } else {
              this.$message.warning(res.message);
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.account {
  .bottom-btn {
    position: absolute;
    bottom: 0px;
    right: 0;
    text-align: right;
    z-index: 2;
  }
}
</style>
