<template>
  <div class="app-container">
    <el-form :model="formData" :rules="rules" ref="companyForm">
      <el-row>
        <el-col :span="11" style="padding-right:30px;">
          <el-form-item label="企业名称：" :label-width="formLabelWidth" prop="name">
            <el-input v-model="formData.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="企业类型：" :label-width="formLabelWidth" prop="typeId">
            <!-- 企业类型的下拉菜单 -->
            <el-select v-model="formData.typeId" placeholder="请选择企业类型">
              <el-option label="政府机关" :value="1"></el-option>
              <el-option label="研究机构" :value="2"></el-option>
              <el-option label="社会团体" :value="3"></el-option>
              <el-option label="企事业单位" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="统一社会信用代码：" :label-width="formLabelWidth" prop="code">
            <el-input v-model="formData.code" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="法人证件类型：" :label-width="formLabelWidth" prop="ceId">
            <!-- 法人证件类型的下拉菜单 -->
            <el-select v-model="formData.ceId" placeholder="请选择法人证件类型">
              <el-option label="中国居民身份证" :value="1"></el-option>
              <el-option label="港澳居民往来内地通行证" :value="2"></el-option>
              <el-option label="台湾居民往来大陆通行证" :value="3"></el-option>
              <el-option label="外国人永久居留身份证" :value="4"></el-option>
              <el-option label="港澳台居民居住证" :value="5"></el-option>
              <el-option label="护照" :value="6"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="法人证件号码：" :label-width="formLabelWidth" prop="enCeNumber">
            <el-input v-model="formData.enCeNumber" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2" style="height:1px;"></el-col>
        <el-col :span="11" style="padding-right:30px;">
          <el-form-item label="所属行业：" :label-width="formLabelWidth" prop="inBigId">
            <!-- 行业大类的下拉菜单 -->
            <el-select
                v-model="formData.inBigId"
                placeholder="行业大类"
                style="width:calc(50% - 10px);margin-right: 20px;"
                @change="changeSmallIndustry(true)"
            >
              <el-option
                  v-for="(item,index) in bigIndustryType"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
              ></el-option>
            </el-select>
            <!-- 行业小类的下拉菜单 -->
            <el-select
                v-model="formData.inSmallId"
                placeholder="行业小类"
                style="width:calc(50% - 10px);"
            >
              <el-option
                  v-for="(item,index) in smallIndustryType"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="法人姓名：" :label-width="formLabelWidth" prop="enLegalName">
            <el-input v-model="formData.enLegalName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="法人证件：" :label-width="formLabelWidth" prop="enCeAddressZ">
            <div class="flex-box">
              <el-upload
                  class="avatar-uploader flex-1"
                  :action="upload_file"
                  :headers="upload_headers"
                  :data="upload_data"
                  :show-file-list="false"
                  :on-success="handlePhotoSuccess"
                  :before-upload="beforeAvatarUpload"
              >
                <img v-if="photoUrl" :src="photoUrl" class="avatar"/>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <el-upload
                  class="avatar-uploader flex-1"
                  :action="upload_file"
                  :headers="upload_headers"
                  :data="upload_data"
                  :show-file-list="false"
                  :on-success="handleReverseSuccess"
                  :before-upload="beforeAvatarUpload"
              >
                <img v-if="reversePhotoUrl" :src="reversePhotoUrl" class="avatar"/>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <el-form-item label-width="150px" prop="enCeAddressF"></el-form-item>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="padding-right:30px;">
          <el-form-item label="企业简介：" :label-width="formLabelWidth" prop="enIntroduction">
            <!-- <el-input v-model="formData.enIntroduction" autocomplete="off"></el-input> -->
            <el-input type="textarea" v-model="formData.enIntroduction"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11" style="padding-right:30px;">
          <el-form-item label="组织/单位注册所在地：" :label-width="formLabelWidth" prop="areaId">
            <!-- <v-distpicker @selected="onSelected" class="my-distpicker"></v-distpicker> -->
            <el-select
                v-model="formData.provinceId"
                placeholder="省"
                style="width:calc(33.3% - 7px);margin-right:10px;"
                @change="changeArea(formData.provinceId,1,true)"
            >
              <el-option
                  v-for="(item,index) in provinces"
                  :key="index"
                  :label="item.name"
                  :value="parseInt(item.value)"
              ></el-option>
            </el-select>
            <el-select
                v-model="formData.cityId"
                placeholder="市"
                style="width:calc(33.3% - 7px);margin-right:10px;"
                @change="changeArea(formData.cityId,2,true)"
            >
              <el-option
                  v-for="(item,index) in citys"
                  :key="index"
                  :label="item.name"
                  :value="parseInt(item.value)"
              ></el-option>
            </el-select>
            <el-select v-model="formData.areaId" placeholder="区" style="width:calc(33.3% - 7px);">
              <el-option
                  v-for="(item,index) in areas"
                  :key="index"
                  :label="item.name"
                  :value="parseInt(item.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="官方网址：" :label-width="formLabelWidth" prop="enOffWeb">
            <el-input v-model="formData.enOffWeb" autocomplete="off"></el-input>
          </el-form-item>
          

          <el-form-item label="联系人姓名：" :label-width="formLabelWidth" prop="conName">
            <el-input v-model="formData.conName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="联系人电话：" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="formData.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="联系人邮箱：" :label-width="formLabelWidth" prop="email">
            <el-input v-model="formData.email" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2" style="height:1px;"></el-col>
        <el-col :span="11" style="padding-right:30px;">
          <el-form-item label="注册详细地址：" :label-width="formLabelWidth" prop="enDetAddress">
            <el-input v-model="formData.enDetAddress" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="组织/单位营业执照：" :label-width="formLabelWidth" prop="enOpeAddress">
            <div class="flex-box">
              <el-upload
                  class="avatar-uploader"
                  :action="upload_file"
                  :headers="upload_headers"
                  :data="upload_data"
                  :show-file-list="false"
                  :on-success="handleLicenceSuccess"
                  :before-upload="beforeAvatarUpload"
              >
                <img v-if="businessLicenceUrl" :src="businessLicenceUrl" class="avatar"/>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="form-footer">
        <el-button type="primary" size="mini" @click="submitForm('companyForm')">确定</el-button>
        <el-button
            type="info"
            size="mini"
            @click="resetForm('companyForm')"
        >返回
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import VDistpicker from "v-distpicker";
import {
  // 企业信息的接口
  addEnterprise,
  editEnterprise,
  getBigIndustryList,
  getSmallIndustryList,
  getArea,
  getEnterpriseDetails 
} from "@/api/company";
// 前缀接口
import {
  // 校验规则
  validateEmail,
  validatePhone,
  validateIDCard,
  validateURL
} from "@/utils/validate";

export default {
  name: "companyDetail",
  components: {VDistpicker},
  data() {
    //法人正面照校验
    const checkPhotoZ = (rule, value, callback) => {
      if ("" == value || !value) {
        return callback(new Error("请上传正面法人证件照"));
      } else {
        callback();
      }
    };
    //法人反面照校验
    const checkPhotoF = (rule, value, callback) => {
      if ("" == value || !value) {
        return callback(new Error("请上传反面法人证件照"));
      } else {
        callback();
      }
    };
    //营业执照照校验
    const checkPhotoOpe = (rule, value, callback) => {
      if ("" == value || !value) {
        return callback(new Error("请上传营业执照"));
      } else {
        callback();
      }
    };
    //手机号校验
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        if (validatePhone(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    //网址校验
    const checkURL = (rule, value, callback) => {
      if (value && !validateURL(value)) {
        return callback(new Error("请输入正确格式的网址"));
      } else {
        callback();
      }
    };
    //邮箱校验
    const checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入联系人邮箱"));
      } else {
        if (!validateEmail(value)) {
          return callback(new Error("请输入正确格式的Email"));
        } else {
          callback();
        }
      }
    };
    //身份证件号校验
    const checkIDNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入法人证件号码"));
      } else {
        if (!validateIDCard(value)) {
          return callback(new Error("请输入正确格式的身份证件号码"));
        } else {
          callback();
        }
      }
    };
    return {
      upload_file: config.UPLOAD_URL, //上传图片的接口地址
      upload_headers:{
        token: getToken() || ''
      },
      upload_data:{
        uploadType:'1',
        suffixType:'8',
        folder:'company'
      },
      ID: this.$route.query.id || "", //上一级页面的传参
      formLabelWidth: "180px", //form表单lable宽度
      photoUrl: "", //正面法人证件照
      reversePhotoUrl: "", //反面法人证件照
      businessLicenceUrl: "", //组织/单位营业执照
      provinceValue: "", //注册地的省
      provinces: [], //注册地-省列表
      cityValue: "", //注册地的市
      citys: [], //注册地-市列表
      areaValue: "", //注册地的区域
      areas: [], //注册地-区列表
      formData: {
        //form表单数据
        code: "", //统一社会信用代码
        name: "", //企业名称
        typeId: "", //企业类型id
        inBigId: "", //行业大类型id
        inSmallId: "", //行业小类型id
        enLegalName: "", //法人姓名
        ceId: "", //法人证件类型id
        enCeNumber: "", //法人证件号码
        enIntroduction: "", //企业简介
        enDetAddress: "", //注册地详细地址
        enOffWeb: "", //官网地址
        enCeAddressZ: "", //正面法人证件地址
        enCeAddressF: "", //反面法人证件地址
        enOpeAddress: "", //营业执照地址
        conName: "", //联系人
        phone: "", //联系电话
        email: "", //联系人邮箱
        provinceId: "", //注册省id
        cityId: "", //注册市id
        areaId: "", //注册区id
        deleted:'0',
        auditStatus:'0'
      },
      rules: {
        //form表单校验规则
        name: [{required: true, message: "请输入活动名称", trigger: "blur"}],
        code: [
          {required: true, message: "请输入统一社会信用代码", trigger: "blur"}
        ],

        typeId: [
          {required: true, message: "请选择企业类型", trigger: "click"}
        ],
        inBigId: [
          //必须选择完大类才能选择小类，所以只校验小类就可以了
          {required: true, message: "请选择行业类型", trigger: "click    "}
        ],
        enLegalName: [
          {required: true, message: "请输入法人姓名", trigger: "blur"}
        ],
        ceId: [
          {required: true, message: "请选择法人证件类型", trigger: "click"}
        ],
        enCeNumber: [
          {required: true, message: "请输入法人证件号码", trigger: "blur"}
          // { type: 'number', message: '法人证件号码必须为数字值'}
        ],
        enIntroduction: [
          {required: true, message: "请输入企业简介", trigger: "blur"}
        ],

        enDetAddress: [
          {required: true, message: "请输入注册地详细地址", trigger: "blur"}
        ],
        enOffWeb: [{validator: checkURL, trigger: "blur"}],
        enCeAddressZ: [
          {required: true, validator: checkPhotoZ, trigger: "blur"}
        ],
        enCeAddressF: [
          {required: true, validator: checkPhotoF, trigger: "blur"}
        ],
        enOpeAddress: [
          {required: true, validator: checkPhotoOpe, trigger: "blur"}
        ],
        conName: [
          {required: true, message: "请输入联系人姓名", trigger: "blur"}
        ],
        phone: [{required: true, validator: checkPhone, trigger: "blur"}],
        email: [{required: true, validator: checkEmail, trigger: "blur"}],
        areaId: [
          {required: true, message: "请选择注册区域", trigger: "change"}
        ]
      },
      isEdit: false, //添加 or 修改
      bigIndustryType: [], //行业大类列表
      smallIndustryType: [] //行业小类列表
    };
  },
  mounted() {
    if(this.ID != '')this.isEdit = true
    //企业用户获取自己企业信息
    if (this.isEdit) {
      this.getEnterpriseInfo();
    }
    this.initData();
  },
  methods: {
    //初始化数据
    initData() {
      //获取行业大类列表
      getBigIndustryList().then(res => {
        this.bigIndustryType = res.data;
      });
      this.changeArea("0", 0);
    },
    //省市区变化时动态获取
    changeArea(pid, type, clean) {
      getArea(pid).then(res => {
        if (type == 0) {
          this.provinces = res.data;
        } else if (type == 1) {
          if (clean) {
            this.formData.cityId = "";
            this.formData.areaId = "";
          }
          this.citys = res.data;
        } else if (type == 2) {
          if (clean) {
            this.formData.areaId = "";
          }
          this.areas = res.data;
        }
      });
    },
    //企业用户获取自己企业信息
    getEnterpriseInfo() {
      getEnterpriseDetails(this.ID).then(res => {
        if (res.data) {
          this.formateData(res.data);
        }
      });
    },
    //整理数据
    formateData(param) {
      this.formData = param;
      // this.formData.enCeNumber = parseInt(this.formData.enCeNumber);
      this.photoUrl = this.formData.enCeAddressZ;
      this.reversePhotoUrl = this.formData.enCeAddressF;
      this.businessLicenceUrl = this.formData.enOpeAddress;
      this.changeSmallIndustry();
      this.changeArea(param.provinceId, 1);
      this.changeArea(param.cityId, 2);
    },
    //行业大类变化获取行业小类
    changeSmallIndustry(clean) {
      if (clean) {
        this.formData.inSmallId = "";
      }
      getSmallIndustryList(this.formData.inBigId).then(res => {
        this.smallIndustryType = res.data;
      });
    },
    //组织/单位营业执照图片上传成功的回调
    handleLicenceSuccess(res, file) {
      this.businessLicenceUrl = URL.createObjectURL(file.raw);
      this.formData.enOpeAddress = res.data;
    },
    //法人正面照图片上传成功的回调
    handlePhotoSuccess(res, file) {
      this.photoUrl = URL.createObjectURL(file.raw);
      this.formData.enCeAddressZ = res.data;
    },
    //法人反面照图片上传成功的回调
    handleReverseSuccess(res, file) {
      this.reversePhotoUrl = URL.createObjectURL(file.raw);
      this.formData.enCeAddressF = res.data;
    },
    //图片上传前的检测
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    //添加企业
    addEnterpriseInfo() {
      let temp1 = this.provinces.filter(item => {
        if(item.value == this.formData.provinceId)
        return item
      })
      this.formData.provinceName = temp1[0].name
      let temp2 = this.citys.filter(item => {
        if(item.value == this.formData.cityId)
        return item
      })
      this.formData.cityName = temp2[0].name
      let temp3 = this.areas.filter(item => {
        if(item.value == this.formData.areaId)
        return item
      })
      this.formData.areaName = temp3[0].name
      addEnterprise(this.formData).then(res => {
        this.$message({
          message: "添加成功！",
          type: "success"
        });
        this.$router.go(-1);
      });
    },
    //修改企业信息
    editEnterpriseInfo() {
      delete this.formData.createTime;
      delete this.formData.updateTime;
      editEnterprise(this.formData).then(res => {
        this.$message({
            message: res.message,
            type: res.status == 200 ? 'success' : 'error'
        });
        this.$router.go(-1);
      });
    },
    //form表单校验
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.isEdit) { //添加企业信息
            this.addEnterpriseInfo();
          } else {                   //修改企业信息
            this.editEnterpriseInfo();
          }
        } else {
          return false;
        }
      });
    },
    //form表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.go(-1);
    }
  }
};
</script>


<style rel="stylesheet/scss" lang="scss" scoped>
.el-select {
  width: 100%;
}

.form-footer {
  text-align: center;
}
</style>
<style lang="scss">
.my-distpicker {
  display: flex;

  select {
    // flex: 1;
    width: 100px !important;
  }
}
</style>
