<template>
  <el-form
    ref="ruleForm"
    v-loading="loading"
    :model="ruleForm"
    status-icon
    :rules="rulesThis"
    :size="'small'"
    label-width="100px"
    class="supplierAdd"
  >
    <el-row>
      <el-col :span="6">
        <div class="supplierAdd-title" style="margin: 6px 0 0 10px">基础信息</div></el-col
      >
      <el-col :span="6">
        <el-form-item label="合作状态" prop="coop_state">
          <el-select
            style="width: 100%"
            v-model="ruleForm.coop_state"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="合作状态"
          >
            <el-option
              v-for="item in coop_stateoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="供应商来源" prop="source">
          <el-select
            style="width: 100%"
            v-model="ruleForm.source"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="供应商来源"
          >
            <el-option
              v-for="item in sourceoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="申请类型" prop="type">
          <el-select
            style="width: 100%"
            v-model="ruleForm.type"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="申请类型"
          >
            <el-option
              v-for="item in typeoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="所属类别" prop="category">
          <el-select
            style="width: 100%"
            v-model="ruleForm.category"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="所属类别"
          >
            <el-option
              v-for="item in categoryoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="物流方式" prop="delivery_way">
          <el-select
            style="width: 100%"
            v-model="ruleForm.delivery_way"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="物流方式"
          >
            <el-option
              v-for="item in delivery_wayoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="6"
        ><el-form-item label="供应商类型" prop="supplier_type">
          <el-select
            style="width: 100%"
            v-model="ruleForm.supplier_type"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="供应商类型"
          >
            <el-option
              v-for="item in supplier_typeoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="6">
        <el-form-item label="供应商级别" prop="level">
          <el-select
            style="width: 100%"
            v-model="ruleForm.level"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="供应商级别"
          >
            <el-option
              v-for="item in leveloptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="付款方式" prop="pay_type">
          <el-select
            style="width: 100%"
            v-model="ruleForm.pay_type"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="付款方式"
          >
            <el-option
              v-for="item in pay_typeoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="personid">
          <search-account
            :disabled="type !== 'add' && type !== 'edit'"
            :is-detail="type !== 'add'"
            :value="ruleForm.personid"
            :size="'small'"
            :names="hand_name"
            :placeholder="'负责人名称'"
            @searchChange="handleHandoverName"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item
          label="营业执照"
          prop="supplier_img"
          :disabled="id == 'view'"
          class="activity-upload"
        >
          <div v-if="ruleForm.supplier_img" class="img-find">
            <img
              :src="ruleForm.supplier_img"
              class="avatar hover fl"
              v-viewer
              style="width: 50px; height: 50px"
            />
            <el-link
              class="fl"
              v-if="type !== 'view'"
              :underline="false"
              @click="deleteimg()"
              type="warning"
              style="margin: 0 0 0 16px"
              >删除</el-link
            >
          </div>
          <div class="btnupload" style="position: relative" v-else>
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <file-upload
              v-if="type !== 'view'"
              class="Upload"
              :disabled="id == 'view'"
              :accept="'.jpg,.png,.jpeg'"
              :multiple="true"
              :uploadcondition="beforeAvatarUpload"
              @UploadErrorEvent="UploadErrorEventsupplier_img"
              @UploadSuccessEvent="UploadSuccessEventsupplier_img"
            ></file-upload>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="资质证明" prop="prove_img">
          <div class="good_info_img_div">
            <ul class="clear">
              <template
                v-if="ruleForm && ruleForm.prove_img && ruleForm.prove_img.length > 0"
              >
                <li
                  class="img-show-li"
                  v-viewer
                  v-for="(img, iindex) in ruleForm.prove_img"
                  :key="img + iindex"
                >
                  <div class="img-show-li-div">
                    <img :src="img" class="img-show" alt="" />
                    <i
                      v-if="type === 'add' || type === 'edit'"
                      class="el-icon-close"
                      @click="closeImg(iindex)"
                    ></i>
                  </div>
                </li>
              </template>
              <li
                class="img-show-li"
                v-if="
                  ruleForm &&
                  ruleForm.prove_img &&
                  ruleForm.prove_img.length < 10 &&
                  type !== 'view'
                "
              >
                <div class="activity-upload">
                  <div class="btnupload" style="position: relative">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                    <file-upload
                      class="Upload"
                      :disabled="type !== 'add' && type !== 'edit'"
                      :accept="'.jpg,.png,.jpeg'"
                      :multiple="true"
                      :uploadcondition="beforeAvatarUpload"
                      @UploadErrorEvent="UploadErrorEventgood_info_img"
                      @UploadSuccessEvent="UploadSuccessEventgood_info_img"
                    ></file-upload>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24"><div class="supplierAdd-title">联系人信息</div></el-col>
      <el-col :span="8">
        <el-form-item label="姓名" prop="contactor">
          <el-input
            v-model="ruleForm.contactor"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="姓名"
            maxlength="20"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="ruleForm.mobile"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="手机号"
            maxlength="20"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="电子邮箱" prop="email">
          <el-input
            v-model="ruleForm.email"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="电子邮箱"
            maxlength="50"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="职位" prop="position">
          <el-input
            v-model="ruleForm.position"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="职位"
            maxlength="20"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="座机号" prop="telephone">
          <el-input
            v-model="ruleForm.telephone"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="座机号"
            maxlength="50"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24"> <div class="supplierAdd-title">营业执照信息</div></el-col>

      <el-col :span="16">
        <el-form-item label="供应商名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="供应商名称"
            maxlength="50"
          />
        </el-form-item>
      </el-col>
      <el-col
        :span="8"
        v-if="
          (ruleForm.supplier_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        "
      >
        <el-form-item label="统一社会信用代码" prop="registercode" label-width="140px">
          <el-input
            v-model="ruleForm.registercode"
            :disabled="type == 'view'"
            placeholder="统一社会信用代码"
            maxlength="18"
          />
        </el-form-item>
      </el-col>
      <el-col
        :span="8"
        v-if="
          (ruleForm.supplier_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        "
      >
        <el-form-item label="公司类型" prop="nature">
          <search-company-type
            :value="ruleForm.nature"
            :disabled="type == 'view'"
            :size="'small'"
            :isDetail="false"
            :placeholder="'公司类型'"
            @searchChange="type_search_change"
          />
        </el-form-item>
      </el-col>
      <el-col
        :span="8"
        v-if="
          (ruleForm.supplier_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        "
      >
        <el-form-item label="法人代表" prop="legaler">
          <el-input
            v-model="ruleForm.legaler"
            :disabled="type == 'view'"
            placeholder="法人代表"
            maxlength="20"
          />
        </el-form-item>
      </el-col>
      <el-col
        :span="8"
        v-if="
          (ruleForm.supplier_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        "
      >
        <el-form-item label="成立日期" prop="registertime">
          <el-input
            v-model="ruleForm.registertime"
            :disabled="type == 'view'"
            placeholder="成立日期"
            maxlength="50"
          />
        </el-form-item>
      </el-col>
      <el-col
        :span="24"
        v-if="
          (ruleForm.supplier_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        "
      >
        <el-form-item label="详细地址" prop="addr">
          <el-input
            v-model="ruleForm.addr"
            :disabled="type == 'view'"
            placeholder="详细地址"
            maxlength="200"
          />
        </el-form-item>
      </el-col>

      <el-col
        :span="24"
        v-if="
          (ruleForm.supplier_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        "
      >
        <el-form-item label="运营范围" prop="scope">
          <el-input
            v-model="ruleForm.scope"
            :autosize="{ minRows: 6, maxRows: 6 }"
            type="textarea"
            :disabled="type == 'view'"
            placeholder="运营范围"
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>
      </el-col>

      <el-col
        :span="24"
        style="text-align: right"
        v-if="type === 'add' || type === 'edit'"
      >
        <el-button type="primary" :size="'small'" @click="submitForm">保 存 </el-button>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import asyncRequest from "@/apis/service/serviceParam/supplier";
import resToken from "@/mixins/resToken";
import {
  isLicense,
  isMobile,
  isqz,
  isSpecialSymbol,
  hasSpace,
  isAddr,
  validEmail,
} from "@/utils/validate";
export default {
  name: "supplierAdd",
  mixins: [resToken],
  props: ["showModel", "id", "type", "sitem"],
  data() {
    const validateLicense = (rule, value, callback) => {
      if (value !== "") {
        if (!isLicense(value)) {
          callback(new Error("统一社会信用代码不正确！"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入统一社会信用代码！"));
      }
    };
    const validatemobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空！"));
      } else {
        if (!isMobile(value)) {
          callback(new Error("手机号格式不正确！"));
        } else {
          callback();
        }
      }
    };
    const validatetelephone = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        if (isqz(value)) {
          callback();
        } else {
          callback(new Error("规则为区号[0+2~3位]-固定电话[7~8位]！"));
        }
      }
    };
    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("详细地址填写不规范！"));
        }
      }
    };
    const validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("邮箱不能为空！"));
      } else {
        if (!validEmail(value)) {
          callback(new Error("邮箱格式不正确！"));
        } else {
          callback();
        }
      }
    };
    return {
      loading: false,
      hand_name: "",
      coop_stateoptions: [
        { value: "0", label: "白名单" },
        { value: "1", label: "黑名单" },
      ],
      sourceoptions: [
        { value: "0", label: "客户提供" },
        { value: "1", label: "供应商" },
        { value: "2", label: "公司开发" },
      ],
      typeoptions: [
        { value: "0", label: "正式供应商" },
        { value: "1", label: "临时供应商" },
      ],
      categoryoptions: [
        { value: "0", label: "单品类供应商" },
        { value: "1", label: "多品类供应商" },
      ],
      delivery_wayoptions: [
        { value: "0", label: "供应商发货" },
        { value: "1", label: "公司自提" },
      ],
      supplier_typeoptions: [
        { value: "0", label: "生产厂家" },
        { value: "1", label: "代理商" },
        { value: "2", label: "经销商" },
        { value: "3", label: "分销商" },
        { value: "4", label: "电商平台" },
      ],
      leveloptions: [
        { value: "2", label: "生产厂家" },
        { value: "0", label: "一级代理商" },
        { value: "1", label: "二级代理商" },
      ],
      pay_typeoptions: [
        { value: "0", label: "现结" },
        { value: "1", label: "月清" },
        { value: "2", label: "双月清" },
      ],
      ocr_status: [
        { id: "0", label: "未上传" },
        { id: "1", label: "识别成功" },
        { id: "2", label: "识别失败" },
      ],
      title: "添加供应商",
      showModelThis: this.showModel,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      ruleForm: {},
      rulesThis: this.rules,
      rules: {
        coop_state: [{ required: true, message: "请选择合作状态", trigger: "change" }],
        source: [{ required: true, message: "请选择供应商来源", trigger: "change" }],

        type: [{ required: true, message: "请选择申请类型", trigger: "change" }],
        category: [{ required: true, message: "请选择所属类别", trigger: "change" }],
        delivery_way: [{ required: true, message: "请选择物流方式", trigger: "change" }],

        supplier_type: [
          { required: true, message: "请选择供应商类型", trigger: "change" },
        ],
        level: [{ required: true, message: "请选择供应商级别", trigger: "change" }],
        pay_type: [{ required: true, message: "请选择付款方式", trigger: "change" }],
        prove_img: [
          {
            required: false,
            type: "array",
            message: "请上传资质证明",
            trigger: "change",
          },
        ],
        personid: [
          {
            required: true,
            type: "array",
            message: "请选择负责人",
            trigger: "change",
          },
        ],
        contactor: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        mobile: [{ required: true, validator: validatemobile, trigger: "blur" }],
        email: [{ required: true, validator: validateEmail, trigger: "blur" }],
        telephone: [{ required: false, validator: validatetelephone, trigger: "blur" }],
        position: [{ required: true, message: "职位不能为空", trigger: "blur" }],
        registercode: [{ required: true, validator: validateLicense, trigger: "blur" }],
        name: [{ required: true, message: "供应商名称不能为空", trigger: "blur" }],
        nature: [{ required: true, message: "公司类型不能为空", trigger: "change" }],
        addr: [{ required: true, validator: validateAddr, trigger: "blur" }],
        legaler: [{ required: true, message: "法人代表不能为空", trigger: "blur" }],
        registertime: [
          { required: true, message: "成立时间不能为空", trigger: "change" },
        ],
        scope: [{ required: true, message: "营业执照不能为空", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.hand_name = "";
      this.loading = true;
      this.resetFormData();
      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();
          this.resetFormData();
        }
      });
    },
    resetFormData() {
      const {
        id,
        coop_state,
        source,
        type,
        category,
        delivery_way,
        supplier_type,
        level,
        pay_type,
        supplier_img,
        prove_img,
        contactor,
        mobile,
        position,
        registercode,
        name,
        nature,
        addr,
        legaler,
        registertime,
        scope,
        personid,
        person,
        telephone,
        email,
      } = this.sitem;
      this.hand_name = person || "";
      this.ruleForm = {
        id: id || "",
        coop_state: coop_state || "",
        source: source || "",
        type: type || "",
        category: category || "",
        delivery_way: delivery_way || "",
        supplier_type: supplier_type || "",
        level: level || "",
        pay_type: pay_type || "",
        supplier_img: supplier_img || "",
        prove_img: prove_img ? (prove_img || "").split(",") : [],
        contactor: contactor || "",
        mobile: mobile || "",
        telephone: telephone || "",
        position: position || "",
        registercode: registercode || "",
        name: name || "",
        email: email || "",
        nature: nature || "",
        addr: addr || "",
        legaler: legaler || "",
        registertime: registertime || "",
        scope: scope || "",
        personid: personid ? [personid] : [],
      };
    },
    closeImg(index) {
      this.ruleForm.prove_img.splice(index, 1);
      this.$refs.ruleForm.validateField("prove_img");
    },
    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.prove_img = model.prove_img.toString();
          model.personid = model.personid.toString();
          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", res.data);
          } 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;
        }
      });
    },
    deleteimg() {
      this.ruleForm.supplier_img = "";
      this.$refs.ruleForm.validateField("supplier_img");
    },
    handleHandoverName(e) {
      if (e && e.id) {
        this.ruleForm.personid = [e.id];
      } else {
        this.ruleForm.personid = [];
      }
      this.$refs.ruleForm.validateField("personid");
    },
    type_search_change(e) {
      const { id } = e;
      this.ruleForm.nature = id ? id : "";
      this.$refs.ruleForm.validateField("nature");
    },

    //图片上传成功
    async UploadSuccessEventsupplier_img(data) {
      await this.UploadSuccessEvent(1, data);
    },
    // //图片上传成功
    // async UploadSuccessEventgood_img(data) {
    //   await this.UploadSuccessEvent(2, data);
    // },
    //图片上传成功
    async UploadSuccessEventgood_info_img(data) {
      await this.UploadSuccessEvent(3, data);
    },
    //图片上传成功
    async UploadSuccessEvent(type, data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        if (type === 1) {
          this.ruleForm.supplier_img = url;
          this.$refs.ruleForm.validateField("supplier_img");
        } else if (type === 2) {
          this.ruleForm.good_img = url;
          this.$refs.ruleForm.validateField("good_img");
        } else {
          this.ruleForm.prove_img.push(url);
          this.$refs.ruleForm.validateField("prove_img");
        }
        this.$message.success("图片上传成功!");
      }
    },
    //图片上传失败
    UploadErrorEventsupplier_img(res) {
      this.imgUploadError(1, res);
    },
    // //图片上传失败
    // UploadErrorEventgood_img(res) {
    //   this.imgUploadError(2, res);
    // },
    //图片上传失败
    UploadErrorEventgood_info_img(res) {
      this.imgUploadError(3, res);
    },
    imgUploadError(type, res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.$refs.ruleForm.validateField(
          type === 1 ? "supplier_img" : type === 2 ? "good_img" : "good_info_img"
        );
      }
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false;
      if (
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/jpeg"
      ) {
        isJPG = true;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error("图片格式不正确！");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.supplierAdd {
  .good_info_img_div {
    ul {
      width: 100%;
      li {
        float: left;
        width: 55px;
        height: 55px;
        padding: 0 5px 0 0;
        .img-show-li-div {
          width: 50px;
          height: 50px;
          border: 1px solid #dfe4ed;
          background: #dfe4ed;
          position: relative;
          img.img-show {
            width: 100%;
            height: 100%;
            position: relative;
            display: inline-block;
          }
          i.el-icon-close {
            position: absolute;
            z-index: 2;
            top: 0;
            right: 0;
            color: #dfe4ed;
          }
          &:hover {
            i.el-icon-close {
              cursor: pointer;
              color: #6954f0;
            }
          }
        }
      }
    }
  }
  .supplierAdd-title {
    border-left: 5px solid #006eff;
    margin: 6px 0 25px 10px;
    width: 100%;
    box-sizing: border-box;
    padding: 0 0 0 10px;
  }
}
</style>
