<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="8vh"
    width="600px"
    :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)"
    append-to-body
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -20px">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        status-icon
        :rules="rulesThis"
        label-width="135px"
        class="demo-ruleForm"
      >
        <el-form-item label="收货总数" prop="receipt_quantity">
          <el-input v-model="ruleForm.receipt_quantity" placeholder="收货总数" />
        </el-form-item>
        <el-form-item label="收货联系人" prop="contactor">
          <el-input
            v-model="ruleForm.contactor"
            maxlength="250"
            placeholder="收货联系人"
          />
        </el-form-item>

        <el-form-item label="收货联系电话" prop="mobile">
          <el-input v-model="ruleForm.mobile" maxlength="11" placeholder="收货联系电话" />
        </el-form-item>
        <el-form-item v-if="type == '1'" label="省市区(文件导入)" prop="in_addr">
          <el-input v-model="ruleForm.in_addr" disabled placeholder="省市区(文件导入)" />
        </el-form-item>
        <el-form-item
          :label="type == '1' ? '省市区(系统解析)' : '收货省市区'"
          prop="addr_code"
        >
          <search-area
            :value="ruleForm.areaCode"
            :is-detail="true"
            :names="ruleForm.label"
            placeholder="收货省市区"
            :level="3"
            @searchChange="areaChange($event)"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="addr">
          <el-input v-model="ruleForm.addr" maxlength="250" placeholder="详细地址" />
        </el-form-item>
        <div style="text-align: right">
          <el-button type="primary" @click="submitForm">保 存 </el-button>
          <el-button @click="showModelThis = false">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </div>
      </el-form>
    </el-card>
  </el-dialog>
</template>

<script>
import {
  isnumber,
  isMobile,
  isChinese,
  isEmoticon,
  isSpecialSymbol,
  hasSpace,
  isAddr,
} from "@/utils/validate";
import { province_list, city_list, county_list } from "@/assets/js/area-data";
import asyncRequest from "@/apis/components/addr-add-edit-modal";
export default {
  name: "AddrAddEditModal",
  props: ["showModel", "index", "sitem", "type"],
  data() {
    const validateWeight = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("不能为空!"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("仅支持整数!"));
        } else {
          callback();
        }
      }
    };
    const validatemobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空！"));
      } else {
        if (!isMobile(value)) {
          callback(new Error("手机号格式不正确！"));
        } else {
          callback();
        }
      }
    };
    const validatecontactor = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("联系人不能为空！"));
      } else {
        if (value.length < 2 || value.length > 10) {
          callback(new Error("联系人规则为2~10位汉字！"));
        } else {
          if (!isChinese(value)) {
            callback(new Error("联系人规则为2~10位汉字！"));
          } else if (isEmoticon(value)) {
            callback(new Error("联系人规则为2~10位汉字！"));
          } else {
            callback();
          }
        }
      }
    };
    const validateAddr = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("详细地址不能为空！"));
      } else {
        if (hasSpace(value)) {
          callback(new Error("不能出现回车/换行符！"));
        } else if (isSpecialSymbol(value)) {
          callback(new Error("不能使用英文特殊字符！"));
        } else if (isAddr(value)) {
          callback();
        } else {
          callback(new Error("详细地址填写不规范！"));
        }
      }
    };
    return {
      roleList: [],
      loading: false,
      title: "",
      organizeList: [],
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < new Date().valueOf();
        },
      },
      showModelThis: this.showModel,
      ruleForm: {
        receipt_quantity: "",
        contactor: "",
        mobile: "",
        addr_code: [],
        addr: "",
        id: "",
      },
      rulesThis: this.rules,
      rules: {
        receipt_quantity: [
          {
            required: true,
            validator: validateWeight,
            trigger: "blur",
          },
        ],

        contactor: [
          {
            required: true,
            trigger: "blur",
            validator: validatecontactor,
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: "blur",
          },
        ],

        addr_code: [
          {
            type: "array",
            required: false,
            message: "收货省市区不能为空",
            trigger: "change",
          },
        ],
        addr: [
          {
            required: true,
            validator: validateAddr,
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    itemidChange(e) {
      this.ruleForm.itemid = e;
      this.$refs.ruleForm.validateField("itemid");
    },
    async initForm() {
      this.loading = true;

      if (this.index === -1) {
        this.title = "添加收货地址";
      } else {
        this.title = "修改收货地址";
      }
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },

    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const {
            receipt_quantity,
            contactor,
            mobile,
            addr_code,
            addr_code_name,
            addr,
            in_addr,
            areaCode,
            label,
            id,
          } = this.sitem;

          console.log(this.sitem);

          this.ruleForm = {
            receipt_quantity,
            contactor,
            mobile,
            in_addr: in_addr || "",
            addr_code: addr_code && addr_code.length === 3 ? addr_code : [],
            addr_code_name: addr_code_name || "",
            addr,
            id: id || "",
            areaCode: areaCode ? [areaCode] : [],
            label: label ? [label] : [],
          };
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.showModelThis = false;
          // addr_code_name
          this.$emit("refresh", {
            index: this.index,
            item: {
              ...JSON.parse(JSON.stringify(this.ruleForm)),
              areaCode: Array.isArray(this.ruleForm.areaCode)
                ? this.ruleForm.areaCode[0]
                : this.ruleForm.areaCode,
              label: Array.isArray(this.ruleForm.label)
                ? this.ruleForm.label[0]
                : this.ruleForm.label,
            },
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async areaChange(e) {
      const { code, area_code, label, splitLabel } = e;
      this.ruleForm.addr_code = code ? code.split(",") : [];
      this.ruleForm.areaCode = area_code ? [area_code] : [];
      this.ruleForm.label = label ? [label] : [];
      this.ruleForm.addr_code_name = splitLabel ? splitLabel.split(",").join("/") : "";
      this.$refs.ruleForm.validateField("addr_code");
    },
    // 省市区选择
    async select_area_change(e) {
      this.ruleForm.addr_code = e;
      this.$refs.ruleForm.validateField("addr_code");

      const { addr_code } = this.ruleForm;
      if (addr_code && addr_code.length === 3) {
        const arrCode = addr_code[addr_code.length - 1];
        // console.log(model);
        const { code, data, message } = await asyncRequest.addrall({
          code: arrCode,
        });
        if (code === 0) {
          const { province, city, area } = data;
          const province_name = province && province.name ? province.name : "";
          const city_name = city && city.name ? city.name : "";
          const area_name = area && area.name ? area.name : "";
          this.addrForm.addr_code_name =
            province_name && city_name && area_name
              ? `${province_name}/${city_name}/${area_name}`
              : "";
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
        }
      } else {
        this.addrForm.addr_code_name = "";
      }
    },
    get_code(name1, name2, name3) {
      let name = "";
      let code = [];
      if (name1 && name2 && name3) {
        for (const x in province_list) {
          if (name1 === province_list[x]) {
            code.push(x);
            name += province_list[x];
            break;
          }
        }
        if (code.length === 1) {
          for (const y in city_list) {
            if (name2 === city_list[y]) {
              code.push(y);
              name += "/" + city_list[y];
              break;
            }
          }
        }
        if (code.length === 2) {
          for (const z in county_list) {
            if (name3 === county_list[z]) {
              code.push(z);
              name += "/" + county_list[z];
              break;
            }
          }
        }

        if (code.length === 3) {
          let str1 = "";
          let str2 = "";
          let isok = false;
          str1 = code[0].slice(0, 2);
          str2 = code[1].slice(2, 4);
          if (
            code[1].indexOf(str1) === 0 &&
            code[2].indexOf(str1) === 0 &&
            code[2].indexOf(str2) == 2
          ) {
            isok = true;
          }
          if (!isok) {
            name = "";
            code = [];
          }
        } else {
          name = "";
          code = [];
        }
      }
      return { name: name, code: code };
    },
  },
};
</script>

<style></style>
