<template>
  <el-form
    ref="ruleForm"
    :loading="loading"
    :model="ruleForm"
    status-icon
    :size="'mini'"
    :rules="rules"
    label-width="100px"
    style="width: 100%"
    class="demo-ruleForm"
  >
    <el-row>
      <!-- <el-col :span="12" v-show="return_tag + '' === '2'">
        <el-form-item label="仓库信息" prop="wsm_supplierNo">
          <search-supplier
            :size="'mini'"
            :value="ruleForm.wsm_supplierNo"
            :disabled="!(status + '' === '3' && ppowers.some((i) => i == '3'))"
            :placeholder="'仓库所在公司'"
            :names="wsm_supplier_name"
            :isDetail="true"
            @searchChange="supplierChange"
          />
        </el-form-item>
      </el-col> -->
      <!-- :companyCode="wsm_supplier_code" -->
      <el-col :span="24" v-show="return_tag + '' === '2'">
        <el-form-item prop="wsm_code" label-width="10px">
          <search-stock
            :size="'mini'"
            :value="ruleForm.wsm_code"
            :placeholder="'退库仓库'"
            :disabled="!(status + '' === '3' && ppowers.some((i) => i + '' == '3'))"
            :isDetail="true"
            :isRelation="true"
            :wsmtype="'4'"
            :names="wsm_code_name"
            :companyNo="sitem.customer_code"
            @searchChange="stockChange"
          />
        </el-form-item>
      </el-col>

      <el-col
        :span="24"
        v-if="
          (ruleForm.wsm_code &&
            ruleForm.wsm_code.length === 1 &&
            return_tag + '' === '2') ||
          return_tag == '1'
        "
      >
        <el-col :span="12">
          <el-form-item label="收件人" prop="contactor">
            <el-input
              :disabled="
                return_tag === '2' ||
                !(status + '' === '3' && ppowers.some((i) => i == '3'))
              "
              v-model="ruleForm.contactor"
              maxlength="20"
              placeholder="收件人"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收件人电话" prop="mobile">
            <el-input
              :disabled="
                return_tag + '' === '2' ||
                !(status + '' === '3' && ppowers.some((i) => i == '3'))
              "
              v-model="ruleForm.mobile"
              maxlength="11"
              placeholder="收件人电话"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="退回地址" prop="addr_code">
            <select-area
              :placeholder="'省/市/区'"
              :value="ruleForm.addr_code"
              :is-detail="true"
              :size="'mini'"
              @selectChange="addr_selectChange"
              :disabled="
                return_tag + '' === '2' ||
                !(status + '' === '3' && ppowers.some((i) => i == '3'))
              "
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="10px" prop="addr">
            <el-input
              :disabled="
                return_tag + '' === '2' ||
                !(status + '' === '3' && ppowers.some((i) => i == '3'))
              "
              v-model="ruleForm.addr"
              maxlength="250"
              placeholder="退回地址"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-col>
      <el-col
        :span="24"
        style="text-align: right; padding: 0 0 15px 0"
        v-if="status + '' === '3' && ppowers.some((i) => i == '3')"
      >
        <el-button type="primary" @click="submitForm" size="mini">保 存</el-button>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/sellAfterApply";
import resToken from "@/mixins/resToken";
import { isMobile, isChinese, isEmoticon } from "@/utils/validate";
export default {
  name: "sellAfterApplyDetail",
  props: ["id", "newTime", "sitem"],
  mixins: [resToken],
  data() {
    const validatename = (rule, value, callback) => {
      if (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 {
      loading: false,
      status: "", //存储详情接口返的状态
      showModelThis: this.showModel,
      wsm_supplier_name: "",
      wsm_code_name: "",
      return_tag: "",
      ruleForm: {
        wsm_supplier: "",
        wsm_supplierNo: [],
        wsm_code: [],
        wsm_codeNo: "",
        contactor: "",
        mobile: "",
        addr_code: [],
        addr: "",
      },
      rulesThis: this.rules,
      // 验证规则
      rules: {
        wsm_supplierNo: [
          {
            type: "array",
            required: true,
            trigger: "change",
            message: "请选择仓库所在公司",
          },
        ],
        wsm_code: [
          {
            type: "array",
            required: true,
            trigger: "change",
            message: "请选择退货仓库",
          },
        ],
        contactor: [
          {
            required: true,
            trigger: "blur",
            validator: validatename,
          },
        ],
        mobile: [
          {
            required: true,
            trigger: "blur",
            validator: validatemobile,
          },
        ],
        addr_code: [
          {
            type: "array",
            required: true,
            trigger: "change",
            message: "请选择省市区",
          },
        ],
        addr: [
          {
            required: true,
            trigger: "blur",
            message: "请输入详细地址",
          },
        ],
      },
    };
  },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "sellAfterApplyDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    ppowers() {
      const tran =
        this.$store.getters.roleProcess.find((i) => i.process_type === "SHD") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.status = "";
      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 {
            status,
            returnCode,
            return_wsm,
            addr,
            mobile,
            contactor,
            wsm_supplierNo,
            wsm_supplier,
            wsm_name,
            addr_code,
            addrs_code,
            return_tag,
          } = this.sitem;

          this.status = status;
          this.return_tag = return_tag || "";
          this.wsm_supplier_name = wsm_supplier;
          this.wsm_code_name = wsm_name;
          this.wsm_supplier_code = wsm_supplierNo;

          this.ruleForm = {
            returnCode: returnCode || "",
            wsm_code: return_wsm ? [return_wsm] : [],
            wsm_supplierNo: wsm_supplierNo ? [wsm_supplierNo] : [],
            contactor: contactor || "",
            mobile: mobile || "",
            addr: addr || "",
            addr_code: [],
          };
          if (addr_code) {
            let code_arr = addr_code.split(",");
            this.ruleForm.addr_code = code_arr && code_arr.length === 3 ? code_arr : [];
          }
          this.rulesThis.wsm_supplierNo[0].required = this.return_tag + "" === "2";
          this.rulesThis.wsm_code[0].required = this.return_tag + "" === "2";
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          model.addr_code = model.addr_code.toString();
          model.wsm_code = model.wsm_code.toString();
          delete model["wsm_codeNo"];
          delete model["wsm_supplier"];
          delete model["wsm_supplierNo"];
          console.log(model);
          // let model = {
          //   returnCode: this.ruleForm.returnCode,
          //   wsm_code: this.ruleForm.wsm_codeNo,
          //   addr_code: "",
          //   addr: "",
          //   mobile: "",
          //   contactor: "",
          // };
          const res = await asyncRequest.aftersetwsm(model);
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({
              title: "提交成功",
              message: "",
            });
            this.$emit("refresh", false);
          } 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;
        }
      });
    },

    async supplierChange(e) {
      if (e && e.id) {
        this.wsm_supplier_code = e.code;
        this.ruleForm.wsm_supplierNo = [e.code];
      } else {
        this.ruleForm.wsm_supplier = [];
        this.wsm_supplier_code = "";
      }
      this.ruleForm.wsm_code = "";
      this.wsm_code = [];
      this.ruleForm.contactor = "";
      this.ruleForm.mobile = "";
      this.ruleForm.addr = "";
    },
    async stockChange(e) {
      const { code, contactor, mobile, addr, addr_code, addr_cn } = e;
      console.log(e);
      this.ruleForm.wsm_codeNo = code || "";
      this.ruleForm.wsm_code = code ? [code] : [];
      this.ruleForm.contactor = contactor || "";
      this.ruleForm.mobile = mobile || "";
      this.ruleForm.addr = addr || "";
      const { provice_code, city_code, area_code } = addr_code;
      this.ruleForm.addr_code = code ? [provice_code, city_code, area_code] : [];
    },
    addr_selectChange(e) {
      this.ruleForm.addr_code = e || [];
      this.$refs.ruleForm.validateField("addr_code");
    },
  },
};
</script>

<style lang="scss" scoped></style>
