<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="24" style="margin-bottom: 10px"
        ><div class="supplierAdd-title" style="margin: 6px 0 0 10px">
          基础信息
        </div></el-col
      >
      <el-col :span="8">
        <el-form-item label="供应商性质" prop="supplier_type">
          <el-select
            v-model="ruleForm.supplier_type"
            style="width: 100%"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="供应商性质"
          >
            <el-option
              v-for="item in natureOfSupplierList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="供应商来源" prop="source">
          <el-select
            v-model="ruleForm.source"
            style="width: 100%"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="供应商来源"
          >
            <el-option
              v-for="item in sourceoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="有效期至" prop="expiretime">
          <el-date-picker
            style="width: 100%"
            value-format="yyyy-MM-DD HH:mm:ss"
            :disabled="type !== 'add' && type !== 'edit'"
            v-model="ruleForm['expiretime']"
            placeholder="有效期"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="付款方式" prop="pay_type">
          <el-select
            v-model="ruleForm.pay_type"
            style="width: 100%"
            :disabled="type !== 'add' && type !== 'edit'"
            placeholder="付款方式"
          >
            <el-option
              v-for="item in pay_typeoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="营业执照"
          prop="license_img"
          :disabled="id == 'view'"
          class="activity-upload"
        >
          <div v-if="ruleForm.license_img" class="img-find">
            <img
              v-viewer
              :src="ruleForm.license_img"
              class="avatar hover fl"
              style="width: 50px; height: 50px"
            />
            <el-link
              v-if="type !== 'view'"
              class="fl"
              :underline="false"
              type="warning"
              style="margin: 0 0 0 16px"
              @click="deleteimg()"
              >删除</el-link
            >
          </div>
          <div v-else class="btnupload" style="position: relative">
            <i class="el-icon-plus avatar-uploader-icon" />
            <file-upload
              v-if="type !== 'view'"
              class="Upload"
              :disabled="type !== 'add' && type !== 'edit'"
              :accept="'.jpg,.png,.jpeg'"
              :multiple="true"
              :uploadcondition="beforeAvatarUpload"
              @UploadErrorEvent="UploadErrorEvent($event, imageProp)"
              @UploadSuccessEvent="UploadSuccessEvent($event, imageProp)"
            />
          </div>
        </el-form-item>
      </el-col>

      <el-col :span="24"><div class="supplierAdd-title">行业信息</div></el-col>
      <table-editor
        mode="modal"
        :readonly="type !== 'add' && type !== 'edit'"
        title="行业"
        :columns="columns"
        :rules="tableRules"
        ref="editor"
        :data.sync="ruleForm.industry"
        @row-update="handleRowUpdate"
      />

      <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="11"
          />
        </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="24"> <div class="supplierAdd-title">营业执照信息</div></el-col>

      <el-col :span="8" v-if="!ruleForm.license_img">
        <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="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.license_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        "
      >
        <el-form-item label="公司类型" prop="nature">
          <el-select
            v-model="ruleForm.nature"
            style="width: 100%"
            placeholder="公司类型"
            :disabled="type !== 'add' && type !== 'edit'"
          >
            <el-option
              v-for="option in supplier_typeoptions"
              :key="option.value"
              :value="option.value"
              :label="option.label"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8"   v-if="
          (ruleForm.license_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.license_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        " >
        <el-form-item label="成立日期" prop="registertime">
          <el-date-picker
            style="width: 100%"
            v-model="ruleForm['registertime']"
            placeholder="成立日期"
            :disabled="type == 'view'"
            value-format="yyyy-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24"   v-if="
          (ruleForm.license_img === '' && (type === 'add' || type == 'edit')) ||
          type == 'view'
        ">
        <el-form-item label="详细地址" prop="register_addr">
          <el-input
            v-model="ruleForm.register_addr"
            :disabled="type == 'view'"
            placeholder="详细地址"
            maxlength="200"
          />
        </el-form-item>
      </el-col>

      <el-col :span="24"   v-if="
          (ruleForm.license_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
        v-if="type === 'add' || type === 'edit'"
        :span="24"
        style="text-align: right"
      >
        <el-button type="primary" :size="'small'" @click="submitForm">保 存 </el-button>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import asyncRequest from "@/apis/service/operate/supplier";
import resToken from "@/mixins/resToken";
import {
  isLicense,
  isMobile,
  isSpecialSymbol,
  hasSpace,
  isAddr,
  validEmail,
} from "@/utils/validate";

/**
 * @props
 * 供应商性质 supplier_type
 * 供应商来源 source
 * 有效期 expiretimeßß
 * 付款方式 pay_type
 * 营业执照 license_img
 * 姓名 contactor
 * 手机号 mobile
 * 电子邮箱 email
 * 职位 position
 * 注册号 registercode
 * 供应商名称 name
 * 公司类型 nature
 * 法人代表 legaler
 * 成立日期 registertime
 * 详细地址 register_addr
 * 运营范围 scope
 *
 */
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 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: "",
      sourceoptions: [
        { value: "1", label: "客户提供" },
        { value: "2", label: "供应商" },
        { value: "3", label: "公司开发" },
      ],
      typeoptions: [
        { value: "0", label: "正式供应商" },
        { value: "1", label: "临时供应商" },
      ],
      categoryoptions: [
        { value: "0", label: "单品类供应商" },
        { value: "1", label: "多品类供应商" },
      ],
      supplier_typeoptions: [
        { 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: "1", label: "现结" },
        { value: "2", label: "月清" },
        { value: "3", label: "双月清" },
      ],
      ocr_status: [
        { id: "0", label: "未上传" },
        { id: "1", label: "识别成功" },
        { id: "2", label: "识别失败" },
      ],
      columns: [
        {
          prop: "industry_id",
          label: "请选择行业",
          type: "select",
          options: [],
        },
        {
          prop: "industry_img",
          label: "行业资质",
          type: "select",
          options: [
            { label: "需要", value: "1" },
            { label: "不需要", value: "0" },
          ],
        },
        {
          prop: "image",
          label: "行业资质图片",
          type: "image",
        },
      ],
      tableRules: {
        industry_id: [
          {
            required: true,
            trigger: "change",
            message: "请选择行业",
          },
        ],
        industry_img: [
          {
            required: true,
            trigger: "change",
            message: "请选择行业资质",
          },
        ],
        image: [
          {
            required: true,
            trigger: "blur",
            message: "请上传行业资质图片",
          },
        ],
      },
      title: "添加供应商",
      showModelThis: this.showModel,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      ruleForm: {
        industry: [],
      },
      rulesThis: this.rules,
      natureOfSupplierList: [
        { value: "1", label: "公务公司" },
        { value: "2", label: "服务商" },
      ],
      rules: {
        supplier_type: [
          { required: true, message: "请选择供应商性质", trigger: "change" },
        ],
        source: [{ required: true, message: "请选择供应商来源", trigger: "change" }],
        expiretime: [{ required: true, message: "请选择有效期", trigger: "change" }],
        category: [{ required: true, message: "请选择所属类别", trigger: "change" }],
        level: [{ required: true, message: "请选择供应商级别", trigger: "change" }],
        pay_type: [{ required: true, message: "请选择付款方式", trigger: "change" }],
        contactor: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        mobile: [{ required: true, validator: validatemobile, trigger: "blur" }],
        email: [{ required: true, validator: validateEmail, 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" }],
        register_addr: [{ required: true, validator: validateAddr, trigger: "blur" }],
        legaler: [{ required: true, message: "法人代表不能为空", trigger: "blur" }],
        registertime: [
          { required: true, message: "成立时间不能为空", trigger: "change" },
        ],
      },
    };
  },
  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,
        name,
        source,
        nature,
        legaler,
        pay_type,
        supplier_type,
        registercode,
        register_addr,
        registertime,
        scope,
        person,
        license_img,
        expiretime,
        contactor_info = [],
        industry_info = [],
      } = this.sitem;

      const [citem = {}] = contactor_info;
      const { email, mobile, contactor, position } = citem;

      this.hand_name = person || "";
      this.ruleForm = {
        id: id || "",
        expiretime: expiretime || "",
        industry: industry_info,
        source: source || "",
        supplier_type: supplier_type || "",
        pay_type: pay_type || "",
        license_img: license_img || "",
        contactor: contactor || "",
        mobile: mobile || "",
        position: position || "",
        registercode: registercode || "",
        name: name || "",
        email: email || "",
        nature: nature || "",
        register_addr: register_addr || "",
        legaler: legaler || "",
        registertime: registertime || "",
        scope: scope || "",
      };
    },
    closeImg(index) {
      this.ruleForm.license_img.splice(index, 1);
      this.$refs.ruleForm.validateField("license_img");
    },
    handleRowUpdate({ row }) {
      console.log(row);
      this.tableRules.image = [
        {
          ...this.tableRules.image[0],
          required: row.industry_img === "1",
        },
      ];
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          const model = JSON.parse(JSON.stringify(this.ruleForm));
          // model.license_img = model.license_img.toString()

          const mapProps = {
            contact: ["contactor", "mobile", "email", "position"],
          };

          Object.keys(mapProps).forEach((key) => {
            model[key] = [{}];
            mapProps[key].forEach((property) => {
              model[key][0][property] = model[property];
              delete model[property];
            });
          });

          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 === 1) {
            const title = this.id === "add" ? "添加成功!" : "修改成功!";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh", res.data);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deleteimg() {
      this.ruleForm.license_img = "";
      this.$refs.ruleForm.validateField("license_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 || "";
      this.$refs.ruleForm.validateField("nature");
    },
    // 图片上传成功
    async UploadSuccessEvent(type, data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        if (type === 1) {
          this.ruleForm.license_img = url;
          this.$refs.ruleForm.validateField("license_img");
        } else if (type === 2) {
          this.ruleForm.good_img = url;
          this.$refs.ruleForm.validateField("good_img");
        } else {
          this.ruleForm.license_img.push(url);
          this.$refs.ruleForm.validateField("license_img");
        }
        
      }
    },
    // 图片上传失败
    UploadErrorEventgood_info_img(res) {
      this.imgUploadError(3, res);
    },
    imgUploadError(type, res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.$refs.ruleForm.validateField(
          type === 1 ? "license_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;
    },
    closeImg(index, key = "license_img") {
      this.ruleForm[key].splice(index, 1);
      this.$refs.ruleForm.validateField(key);
    },
    async UploadSuccessEvent(data, key = "license_img") {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm[key] = url;
        this.$refs.ruleForm.validateField(key);
        
      }
    },
    UploadErrorEvent(res, key = "license_img") {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.$refs.ruleForm.validateField(key);
      }
    },
    async onSubmit() {
      try {
        await this.$refs.ruleForm.validate();
        this.$emit("confirm", this.ruleForm);
      } catch (err) {
        console.log(err);
      }
    },
  },
};
</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>
