<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="8vh"
    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="70px"
            class="demo-ruleForm"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="姓名" prop="nickname">
                  <el-input
                    v-model="ruleForm.nickname"
                    :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="24">
                <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="supplierNo">
                  <el-table
                    :data="ruleForm.supplierNo"
                    stripe
                    border
                    style="width: 100%"
                    :size="'mini'"
                    max-height="450px"
                  >
                    <el-table-column prop="supplierNo" label="供应商编码" width="180">
                    </el-table-column>
                    <el-table-column
                      prop="supplierName"
                      label="供应商名称"
                      min-width="180"
                    >
                    </el-table-column>

                    <el-table-column fixed="right" width="50">
                      <template slot="header" slot-scope="scope">
                        <span>操作</span>
                      </template>
                      <template slot-scope="scope">
                        <el-tooltip
                          effect="dark"
                          v-if="!isDetail"
                          content="删除"
                          placement="top"
                        >
                          <i
                            class="el-icon-delete tb-icon"
                            @click="deleteRow(scope.$index, ruleForm.supplierNo)"
                          ></i>
                        </el-tooltip>
                      </template>
                    </el-table-column>
                  </el-table>

                  <!-- <el-input
                    v-model="ruleForm.supplierNo"
                    :placeholder="'邮箱'"
                    maxlength="100"
                    :disabled="isDetail"
                  /> -->
                </el-form-item>
              </el-col>
              <el-col :span="24" class="tr">
                <el-button
                  v-if="!isDetail"
                  type="primary"
                  @click="submitForm"
                  :size="'mini'"
                  >保 存
                </el-button>
                <el-button @click="showModelThis = false" :size="'mini'">{{
                  isDetail ? "关 闭" : "取 消"
                }}</el-button>
                <div class="fl tl" v-if="!isDetail" style="width: 450px">
                  <span>添加供应商:</span>
                  <search-supplier
                    :size="'mini'"
                    style="width: 370px"
                    :value="supplierNo"
                    :disabled="false"
                    :placeholder="'供应商名称'"
                    :names="''"
                    :isDetail="false"
                    @searchChange="supplierChange"
                  />
                </div>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/serviceParam/supplierAccount";
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 validatename = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("真实姓名不能为空！"));
      } else {
        callback();
        // 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: [],
      supplierNo: "",
      is_mainoptions: [],
      isIndeterminate: false,
      ruleForm: {
        uid: "",
        supplierNo: [],
        nickname: "", // 真实姓名
        mobile: "",
        email: "",
      },
      platformoptions: [],
      rulesThis: this.rules,
      rules: {
        nickname: [
          {
            required: true,
            validator: validatename,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: "blur",
          },
        ],
        email: [
          {
            required: false,
            validator: validateEmail,
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  mounted() {},
  methods: {
    async initForm() {
      this.loading = true;
      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 initData() {
      const { code, data, message } = await asyncRequest.detail({
        uid: this.id,
      });
      if (code === 0) {
        await this.resetForm(data);
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    async supplierChange(e) {
      const { code, label } = e;
      const scode = code ?? "";
      if (scode !== "") {
        const list = this.ruleForm.supplierNo;
        const index = list.findIndex((si) => si.supplierNo === scode);
        if (index === -1) {
          this.ruleForm.supplierNo.push({
            id: "",
            supplierNo: scode,
            supplierName: label,
          });
        } else {
          this.$message.warning("该供应商已添加！");
        }
      }

      // this.parmValue.supplierNo = code ? [code] : [];
    },
    async resetForm(sitem) {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          if (sitem) {
            const {
              uid,
              supplier_list,
              nickname, // 真实姓名
              mobile,
              email,
            } = sitem;

            this.ruleForm = {
              uid,
              supplierNo: supplier_list,
              nickname, // 真实姓名
              mobile,
              email,
            };
          } else {
            this.ruleForm = {
              id: "",
              supplierNo: [],
              nickname: "", // 真实姓名
              mobile: "",
              email: "",
            };
          }
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (!this.loading) {
            this.loading = true;
            let model = JSON.parse(JSON.stringify(this.ruleForm));
            const { supplierNo } = model;

            if (supplierNo.length === 0) {
              this.$message.warning("至少关联一个供应商！");
              this.loading = false;
              return;
            }
            let res = {};
            if (this.id === "add") {
              delete model["uid"];
              let arr = [];
              supplierNo.forEach((a) => {
                arr.push(a.supplierNo);
              });
              model.supplierNo = arr;
              console.log(model);
              res = await asyncRequest.add(model);
            } else {
              let arr2 = [];
              supplierNo.forEach((a) => {
                let iitem = {
                  supplierNo: a.supplierNo,
                  supplierName: a.supplierName,
                };
                if (a.id) {
                  iitem.id = a.id;
                }
                arr2.push(iitem);
              });
              model.supplier_list = arr2;
              delete model["supplierNo"];
              console.log(model);
              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>
