<template>
  <el-dialog
    :title="title"
    :center="true"
    align="left"
    top="8vh"
    width="600px"
    @close="showModelThis = false"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
  >
    <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" 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"
        >
          <select-area
            :value="ruleForm.addr_code"
            placeholder="收货省市区"
            @selectChange="select_area_change($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 } 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();
        }
      }
    };
    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",
            message: "联系人不能为空",
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: "blur",
          },
        ],

        addr_code: [
          {
            type: "array",
            required: true,
            message: "收货省市区不能为空",
            trigger: "change",
          },
        ],
        addr: [
          {
            required: true,
            message: "详细地址不能为空",
            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,
            id,
          } = 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 || "",
          };
        }
      });
    },
    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)),
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //省市区选择
    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) {
        let arrCode = addr_code[addr_code.length - 1];
        // console.log(model);
        let { code, data, message } = await asyncRequest.addrall({
          code: arrCode,
        });
        if (code === 0) {
          const { province, city, area } = data;
          let province_name = province && province.name ? province.name : "";
          let city_name = city && city.name ? city.name : "";
          let 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 = "",
        code = [];
      if (name1 && name2 && name3) {
        for (let x in province_list) {
          if (name1 === province_list[x]) {
            code.push(x);
            name += province_list[x];
            break;
          }
        }
        if (code.length === 1) {
          for (let y in city_list) {
            if (name2 === city_list[y]) {
              code.push(y);
              name += "/" + city_list[y];
              break;
            }
          }
        }
        if (code.length === 2) {
          for (let z in county_list) {
            if (name3 === county_list[z]) {
              code.push(z);
              name += "/" + county_list[z];
              break;
            }
          }
        }

        if (code.length === 3) {
          let str1 = "",
            str2 = "",
            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>