<template>
  <el-dialog
    :title="title"
    :center="true"
    align="left"
    top="8vh"
    width="1040px"
    @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)"
  >
    <el-card style="margin-top: -20px">
      <el-row>
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :size="'small'"
            :rules="rulesThis"
            label-width="90px"
            class="demo-ruleForm"
          >
            <el-row style="">
              <el-col :span="1" style="height: 336px; border-right: 1px solid #dcdfe6">
                <ul class="tc fff">
                  <li>企</li>
                  <li>业</li>
                  <li>信</li>
                  <li>息</li>
                </ul>
              </el-col>
              <el-col :span="23">
                <el-row>
                  <el-col :span="13">
                    <el-form-item label="企业名称" prop="company">
                      <el-input
                        placeholder="企业名称"
                        filterable
                        :disabled="isDetail == '007'"
                        maxlength="100"
                        clearable
                        v-model="ruleForm.company"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="11"
                    ><el-form-item
                      label="统一社会信用代码"
                      prop="inv_code"
                      label-width="150px"
                      style="width: 100%"
                    >
                      <el-input
                        placeholder="统一社会信用代码"
                        filterable
                        :disabled="isDetail == '007'"
                        maxlength="40"
                        clearable
                        v-model="ruleForm.inv_code"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="13">
                    <el-form-item label="详细地址" prop="inv_addr">
                      <el-input
                        placeholder="详细地址"
                        v-model="ruleForm.inv_addr"
                        maxlength="100"
                        clearable
                        :disabled="isDetail == '007'"
                      >
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="法人" prop="inv_legaler">
                      <el-input
                        placeholder="法人"
                        v-model="ruleForm.inv_legaler"
                        maxlength="12"
                        minlength="2"
                        clearable
                        :disabled="isDetail == '007'"
                      /> </el-form-item
                  ></el-col>
                  <el-col :span="13">
                    <el-form-item label="成立日期" prop="inv_time">
                      <el-date-picker
                        style="width: 100%"
                        v-model="ruleForm.inv_time"
                        align="right"
                        type="date"
                        placeholder="成立日期"
                        value-format="yyyy-MM-dd"
                        :picker-options="pickerOptions"
                      >
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="联系人" prop="contactor">
                      <el-input
                        placeholder="联系人"
                        v-model="ruleForm.contactor"
                        maxlength="12"
                        minlength="2"
                        clearable
                        :disabled="isDetail == '007'"
                      /> </el-form-item
                  ></el-col>
                  <el-col :span="13">
                    <el-form-item label="营业范围" prop="inv_scope">
                      <el-input
                        v-model="ruleForm.inv_scope"
                        type="textarea"
                        placeholder="营业范围"
                        maxlength="2000"
                        :rows="8"
                        show-word-limit
                        :disabled="isDetail == '007'"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="11">
                    <el-form-item label="公司类型" prop="type">
                      <search-company-type
                        :value="ruleForm.type"
                        :disabled="false"
                        :size="'mini'"
                        :isDetail="false"
                        :placeholder="'公司类型'"
                        @searchChange="type_search_change"
                      /> </el-form-item
                  ></el-col>

                  <el-col :span="11" style="height: 124px">
                    <el-form-item
                      label="营业执照"
                      prop="license_img"
                      class="activity-upload"
                    >
                      <div class="btnupload" style="position: relative">
                        <img
                          v-if="ruleForm.license_img"
                          :src="ruleForm.license_img"
                          class="avatar"
                        />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        <file-upload
                          class="Upload"
                          :disabled="isDetail == '007'"
                          :accept="'.jpg,.png,.jpeg'"
                          :multiple="true"
                          :uploadcondition="beforeAvatarUpload"
                          @UploadErrorEvent="UploadErrorEvent"
                          @UploadSuccessEvent="UploadSuccessEvent"
                        ></file-upload>
                      </div>
                      <div class="txt-tips fl">
                        <p>大小：小于1M</p>
                        <p>尺寸：100*100</p>
                        <p>类型：jpg.png.jpeg</p>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <el-row style="border-top: 1px solid #dcdfe6">
              <el-col
                :span="1"
                style="
                  height: 120px;
                  padding: 20px 0 0 0;
                  border-right: 1px solid #dcdfe6;
                "
              >
                <ul class="tc sss">
                  <li>开</li>
                  <li>票</li>
                  <li>信</li>
                  <li>息</li>
                </ul>
              </el-col>
              <el-col :span="23" style="padding: 20px 0 0 0">
                <el-row>
                  <el-col :span="13">
                    <el-form-item label="银行名称" prop="inv_bank">
                      <el-input
                        v-model="ruleForm.inv_bank"
                        placeholder="银行名称"
                        :disabled="isDetail == '007'"
                        maxlength="100"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="银行卡号" prop="inv_bankNo">
                      <el-input
                        v-model="ruleForm.inv_bankNo"
                        placeholder="银行卡号"
                        maxlength="100"
                        :disabled="isDetail == '007'"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="13">
                    <el-form-item label="联系地址" prop="addr">
                      <el-input
                        v-model="ruleForm.addr"
                        placeholder="联系地址"
                        maxlength="100"
                        :disabled="isDetail == '007'"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="联系电话" prop="mobile">
                      <el-input
                        v-model="ruleForm.mobile"
                        placeholder="联系电话"
                        maxlength="100"
                        :disabled="isDetail == '007'"
                      />
                    </el-form-item>
                    <div style="width: 100%; text-align: right">
                      <el-button
                        type="primary"
                        :size="'small'"
                        @click="submitForm"
                        v-if="isDetail !== '007'"
                        >保 存
                      </el-button>
                      <el-button :size="'small'" @click="showModelThis = false">{{
                        isDetail == "007" ? "关 闭" : "取 消"
                      }}</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/serviceParam/workCompany";
import resToken from "@/mixins/resToken";
import {
  isMobile,
  isLicense,
  isPhone,
  isChinese,
  isEmoticon,
  isSpecialSymbol,
  hasSpace,
  isAddr,
} from "@/utils/validate";
export default {
  name: "workCompany",
  props: ["showModel", "id", "isDetail"],
  mixins: [resToken],
  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 !== "") {
        if (isPhone(value) || isMobile(value)) {
          callback();
        } else {
          callback(new Error("联系电话格式不正确！"));
        }
      } else {
        callback(new Error("联系电话不能为空！"));
      }
    };
    const validatename = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("法人不能为空！"));
      } else {
        if (!isChinese(value)) {
          callback(new Error("法人只能为汉字！"));
        } else if (isEmoticon(value)) {
          callback(new Error("法人只能为汉字！"));
        } else {
          callback();
        }
      }
    };
    const validatecontactor = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("联系人不能为空！"));
      } else {
        if (!isChinese(value)) {
          callback(new Error("联系人只能为汉字！"));
        } else if (isEmoticon(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("详细地址填写不规范！"));
        }
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() >= Date.now();
        },
      },
      supplier_name: "",
      accountNames: "",
      loading: false,
      title: "添加业务企业",
      showModelThis: this.showModel,
      ruleForm: {
        id: "",
        company: "", //公司名称
        type: "", //	公司类型
        inv_code: "", //	纳税识别号
        inv_legaler: "", //	法人
        inv_time: "", //注册日期
        inv_addr: "", //注册地址
        inv_bank: "", //	银行
        inv_bankNo: "", //	银行账户
        contactor: "", //		联系人
        mobile: "", //	联系人电话
        addr: "", //		联系地址
        inv_scope: "", //	经营范围
        license_img: "", //	营业执照
      },
      rulesThis: this.rules,
      rules: {
        company: [{ required: true, message: "企业名称不能为空!", trigger: "blur" }],
        type: [
          {
            required: true,
            message: "公司类型不能为空！",
            trigger: "change",
          },
        ],
        inv_code: [
          {
            required: true,
            validator: validateLicense,
            trigger: "blur",
          },
        ],
        inv_legaler: [
          {
            required: true,
            validator: validatename,
            trigger: "blur",
          },
        ],

        inv_time: [
          {
            required: true,
            message: "成立日期不能为空！",
            trigger: "change",
          },
        ],
        inv_addr: [
          {
            required: true,
            validator: validateAddr,
            trigger: "blur",
          },
        ],
        inv_bank: [
          {
            required: true,
            message: "银行名称不能为空！",
            trigger: "blur",
          },
        ],
        inv_bankNo: [
          {
            required: true,
            message: "银行卡号不能为空！",
            trigger: "blur",
          },
        ],
        contactor: [
          {
            required: true,
            validator: validatecontactor,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: "blur",
          },
        ],
        addr: [{ required: true, message: "联系地址不能为空！", trigger: "blur" }],
        inv_scope: [{ required: true, message: "经营范围不能为空！", trigger: "blur" }],
        license_img: [
          {
            required: false,
            message: "",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    async initForm() {
      this.supplier_name = "";
      this.loading = true;
      if (this.isDetail === "003") {
        this.title = "新建业务企业";
        this.rulesThis = this.rules;
        await this.resetForm();
      } else if (this.isDetail == "007") {
        this.title = "业务企业详情";
        this.rulesThis = {};
        await this.resetForm();
        await this.initData();
      } else {
        this.title = "修改业务企业";
        this.rulesThis = this.rules;
        await this.resetForm();
        await this.initData();
      }
      this.loading = false;
    },
    type_search_change(e) {
      console.log(e);
      const { id, code, label } = e;
      if (id) {
        this.ruleForm.type = id;
      } else {
        this.ruleForm.type = "";
      }
      this.$refs.ruleForm.validateField("type");
    },

    async initData() {
      const res = await asyncRequest.detail({ companyNo: this.id });
      if (res && res.code === 0 && res.data) {
        const {
          id,
          company, //公司名称
          type, //	公司类型
          inv_code, //	纳税识别号
          inv_legaler, //	法人
          inv_time, //注册日期
          inv_addr, //注册地址
          inv_bank, //	银行
          inv_bankNo, //	银行账户
          contactor, //		联系人
          mobile, //	联系人电话
          addr, //		联系地址
          inv_scope, //	经营范围
          license_img, //	营业执照
        } = res.data;

        this.ruleForm = {
          id: id || "",
          company: company || "", //公司名称
          type: type || "", //	公司类型
          inv_code: inv_code || "", //	纳税识别号
          inv_legaler: inv_legaler || "", //	法人
          inv_time: inv_time || "", //注册日期
          inv_addr: inv_addr || "", //注册地址
          inv_bank: inv_bank || "", //	银行
          inv_bankNo: inv_bankNo || "", //	银行账户
          contactor: contactor || "", //		联系人
          mobile: mobile || "", //	联系人电话
          addr: addr || "", //		联系地址
          inv_scope: inv_scope || "", //	经营范围
          license_img: license_img || "", //	营业执照
        };
        console.log(this.ruleForm);
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            id: "",
            company: "", //公司名称
            type: "", //	公司类型
            inv_code: "", //	纳税识别号
            inv_legaler: "", //	法人
            inv_time: "", //注册日期
            inv_addr: "", //注册地址
            inv_bank: "", //	银行
            inv_bankNo: "", //	银行账户
            contactor: "", //		联系人
            mobile: "", //	联系人电话
            addr: "", //		联系地址
            inv_scope: "", //	经营范围
            license_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));

          let res = {};
          if (this.isDetail === "003") {
            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.isDetail === "003" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh");
          } 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;
        }
      });
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false,
        isLt2M = false;
      if (file) {
        if (
          file.type === "image/jpg" ||
          file.type === "image/png" ||
          file.type === "image/jpeg"
        ) {
          isJPG = true;
        }
        isLt2M = file.size / 1024 / 1024 < 1;
        if (!isJPG) {
          this.$message.error("图片格式不正确！");
        }
        if (!isLt2M) {
          this.$message.error("图片大小不能超过 1MB!");
        }
      }

      return isJPG && isLt2M;
    },
    //图片上传失败
    UploadErrorEvent(res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.ruleForm.license_img = "";
        this.$refs.ruleForm.validateField("license_img");
      }
    },
    //图片上传成功
    async UploadSuccessEvent(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.license_img = url;
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("license_img");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.workCompany {
  .fff,
  .sss {
    // border-right: 1px solid #DCDFE6;
    box-sizing: border-box;
    li {
      line-height: 20px;
      font-size: 16px;
      font-weight: bold;
      height: 20px;
    }
  }
  .fff {
    padding: 115px 0 0 0;
  }
}
</style>
