<template>
  <!-- 弹出框表单 -->
  <el-drawer
    :title="title"
    :visible.sync="open"
    :direction="direction"
    :destroy-on-close="true"
    size="80%"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="140px" style="padding:0 40px;">
      <el-row>
        <Field label="企业名称" prop="companyName" v-model="form.companyName" placeholder="请输入企业名称" />
        <Field label="联系电话" prop="contactPhone" v-model="form.contactPhone" placeholder="请输入联系电话" />
        <!-- <Field label="公司编码" prop="companyCode" v-model="form.companyCode" placeholder="请输入公司编码"/>
                            <Field label="注册号" prop="registrationNumber" v-model="form.registrationNumber" placeholder="请输入注册号"/>
                            <Field label="法定代表人" prop="legalRepresentative" v-model="form.legalRepresentative" placeholder="请输入法定代表人"/>
                            <Field label="注册资本" prop="registeredCapital" v-model="form.registeredCapital" placeholder="请输入注册资本"/>
                            <Field label="公司类型" prop="companyType" v-model="form.companyType" placeholder="请输入公司类型"/>
        <Field :span="24" label="经营范围" prop="businessScope" v-model="form.businessScope" placeholder="请输入经营范围"/>-->
        <!-- <Field :span="24" label="经营地址" prop="businessAdress" v-model="form.businessAdress" placeholder="请输入经营地址">
                              <p>当前选中的行政区划编码为： {{regionCodeList}}</p>
                              <el-cascader  v-model="regionCodeList" :props="areaprops"></el-cascader>
        </Field>-->

        <Field
          :span="24"
          label="经营地址"
          prop="businessAdress"
          placeholder="请输入经营地址"
        >
          <area-select ref="areaselect" v-model="form.areaCode" @addressSelect="addressSelect"></area-select>
        </Field>

        <!-- <Field label="所在地" prop="location" v-model="form.location" placeholder="请输入所在地"/> -->
        <Field prop="location" v-model="form.location" placeholder="请输入详细地址" />
        <!-- <Field label="电子邮件地址" prop="email" v-model="form.email" placeholder="请输入电子邮件地址"/>
                            <Field label="公司网站" prop="website" v-model="form.website" placeholder="请输入公司网站"/>
                            <Field label="税务登记号" prop="taxRegistrationNumber" v-model="form.taxRegistrationNumber" placeholder="请输入税务登记号"/>
                            <Field label="社会信用代码" prop="socialCreditCode" v-model="form.socialCreditCode" placeholder="请输入社会信用代码"/>
                            <Field label="商标信息" prop="trademarkInfo" v-model="form.trademarkInfo" placeholder="请输入商标信息"/>
                            <Field label="网站历史备案信息" prop="websiteRegistrationInfo" v-model="form.websiteRegistrationInfo" placeholder="请输入网站历史备案信息"/>
                            <Field label="员工总数" prop="totalEmployees" v-model="form.totalEmployees"   placeholder="员工总数"/>
                            <Field label="软件著作权数量" prop="softNum" v-model="form.softNum"  placeholder="软件著作权数量"/>
                            <Field label="专利数量" prop="patentNum" v-model="form.patentNum" placeholder="专利数量"/>
                            <Field label="历史发展" prop="hisDevelop" v-model="form.hisDevelop" type="textarea" placeholder="请输入历史发展"/>
                            <Field label="经度" prop="lon" v-model="form.lon" placeholder="请输入经度"/>
        <Field label="纬度" prop="lati" v-model="form.lati" placeholder="请输入纬度"/>-->
        <!-- <Field label="公司文化" prop="companyCulture" v-model="form.companyCulture" type="textarea" placeholder="请输入公司文化"/>
                            <Field label="排序" prop="sort" v-model="form.sort" type="num" placeholder="请输入排序"/>
        <Field label="成立日期" prop="establishDate" v-model="form.establishDate" type="date" />-->

        <Field :span="24" label="企业logo">
          <imageUpload v-model="form.logoPath" prePath="/file/preview" />
        </Field>
        <Field :span="24" label="企业标签">
          <el-select
            v-model="companyLabelsList"
            multiple
            placeholder="请选择企业标签"
            :style="{ width: '590px' }"
          >
            <el-option
              v-for="($label, $value) in dict.labels"
              :key="$value"
              :label="$label"
              :value="$value"
            ></el-option>
          </el-select>
        </Field>
        <Field
          label="公司介绍"
          prop="companyIntroduction"
          v-model="form.companyIntroduction"
          type="textarea"
          placeholder="请输入公司介绍"
        />
        <!-- <Field :span="24" label="企业视频"><fileUpload v-model="form.companyVideoPath" :fileType="[ 'mp4', 'avi']"  prePath="/file/fileupload"/></Field>
              <Field :span="24" label="企业宣传图片"><fileUpload v-model="form.companyPicPath" :fileType="['png', 'jpg', 'jpeg']" prePath="/file/preview"/></Field>

        <Field :span="24" label="备注" prop="remark" v-model="form.remark" type="textarea" placeholder="请输入备注"/>-->
      </el-row>
      <Field :span="24" label="知识产权">
        <el-table
          class="zhshchq"
          :data="companyPatentsList"
          :row-class-name="rowCompanyPatentsIndex"
          @selection-change="handleCompanyPatentsSelectionChange"
          ref="companyPatents"
        >
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="知识产权类型" align="center" prop="intellectPropertyType">
            <template slot-scope="scope">
              <el-input v-model="scope.row.intellectPropertyType" placeholder="请输入知识产权类型" />
            </template>
          </el-table-column>

          <el-table-column label="知识产权数量" prop="labelId" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.intellectPropertyNum"
                size="small"
                placeholder="请输入知识产权数量"
              ></el-input-number>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240">
            <template slot-scope="scope">
              <Confirm @confirm="handleDeleteCompanyPatents(scope.row)" message="确定要删除该条知识产权吗？">
                <div class="del">删除</div>
              </Confirm>
            </template>
          </el-table-column>
        </el-table>
        <el-row
          style="margin:10px 0;display: flex;justify-content: center;"
          :gutter="10"
          class="mb8"
        >
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" @click="handleAddCompanyPatents">新增知识产权</el-button>
          </el-col>
        </el-row>

        <el-form-item v-if="pageInfo.type!='view'" class="formbtns">
          <el-button type="primary" @click="hanndleSubmit" icon="el-icon-circle-check-outline">保存</el-button>
          <el-button @click="open=false" icon="el-icon-circle-close-outline">取消</el-button>
        </el-form-item>
      </Field>
    </el-form>
  </el-drawer>
</template>

<script>
import form from "@/assets/mixins/formdialog";
import Confirm from "@/components/Confirm.vue";
export default {
  name: "CompanyDetail",
  mixins: [form],
  components: {
    Confirm
  },
  created() {
    this.changePath("company");
  },
  data() {
    let that = this;
    var checkPhone = (rule,value,callback) =>{
      let phoneReg = /^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/
      if(!value){
        callback()
      }else{
        if(phoneReg.test(value)){
          callback()
        }else{
          callback(new Error("请输入正确的联系电话"))
        }
      }
    }
    return {
      regionCodeList: [],
      areaprops: {
        // 单选
        checkStrictly: true,
        // 懒加载
        lazy: true,
        lazyLoad(node, resolve) {
          var param = {
            pid: node.level === 0 ? 0 : node.data.id,
            size: -1
          };

          that.$post("/base/area/list", param).then(res => {
            console.log(res);
            let nodes = res.data.data.map(item => {
              return {
                value: item.areaCode,
                label: item.name,
                id: item.iid,
                leaf: item.haveSonArea === "False"
              };
            });
            resolve(nodes);
          });
        }
      },
      // 子表选中数据
      checkedCompanyLabels: [],
      // 公司标注表格数据
      companyLabelsList: [],
      // 子表选中数据
      checkedCompanyPatents: [],
      // 公司专利表格数据
      companyPatentsList: [],
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "公司",
      // 是否显示弹出层
      open: false,
      direction: "rtl",
      toString: ["labelId"],
      toDate: ["establishDate"],
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
          { max: 128, message: "最多只能录入128个字符", trigger: "blur" }
        ],
        areaCode: [
          { required: true, message: "请输入所属区域编码", trigger: "blur" },
          { max: 128, message: "最多只能录入128个字符", trigger: "blur" }
        ],
        areaName: [
          { required: true, message: "请输入所属区域名称", trigger: "blur" },
          { max: 128, message: "最多只能录入128个字符", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { validator: checkPhone,trigger: "blur" },
          { max: 32, message: "最多只能录入32个字符", trigger: "blur" }
        ],
        lon: [
          { required: true, message: "请输入经度", trigger: "blur" },
          { max: 32, message: "最多只能录入32个字符", trigger: "blur" }
        ],
        lati: [
          { required: true, message: "请输入纬度", trigger: "blur" },
          { max: 32, message: "最多只能录入32个字符", trigger: "blur" }
        ],
        logoPath: [
          { required: true, message: "请输入企业logo", trigger: "blur" },
          { max: 128, message: "最多只能录入128个字符", trigger: "blur" }
        ],
        establishDate: [{ required: true, message: "请选择成立日期" }],
        createTime: [{ required: true, message: "请选择创建时间" }]
      }
    };
  },

  methods: {
    hanndleSubmit(){
      this.form.businessAdress = this.$refs.areaselect.provinceName+this.$refs.areaselect.cityName+this.$refs.areaselect.areaName+this.$refs.areaselect.streetName+this.$refs.areaselect.communityName+this.form.location
      // 检查知识产权list中类型不能为空
      if(this.companyPatentsList && this.companyPatentsList.length>0){
        let isNull = false
        this.companyPatentsList.forEach((item)=>{
          if (!item.intellectPropertyType) {
            isNull = true
          }
        })
        if(isNull){
          this.$confirm('知识产权类型不能为空', '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              showCancelButton: false, //是否显示取消按钮
              showClose: false, //是否显示关闭按钮
          })
          return;
        }
      }
      this.submitForm()
    },
    addressSelect(val) {
      console.log("addressSelect", val);
    },

    /** 公司标注序号 */
    rowCompanyLabelsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 公司专利序号 */
    rowCompanyPatentsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 公司专利添加按钮操作 */
    handleAddCompanyPatents() {
      let obj = {};
      obj.companyId = "";
      obj.intellectPropertyType = "";
      obj.intellectPropertyNum = 1;
      obj.remark = "";
      obj.createUserId = "";
      obj.createTime = "";
      obj.updateUserId = "";
      obj.updateTime = "";
      this.companyPatentsList.push(obj);
    },
    /** 公司专利删除按钮操作 */

    handleDeleteCompanyPatents(row) {
      // 由于有一些知识产权还没有id，所以这里删除选用的是字段中带的index
      this.companyPatentsList = this.companyPatentsList.filter(
        item => item.index !== row.index
      );
      this.form.companyPatentsList = this.companyPatentsList;
    },
    /** 单选框选中数据 */
    handleCompanyPatentsSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.companyPatents.clearSelection();
        this.$refs.companyPatents.toggleRowSelection(selection.pop());
      } else {
        this.checkedCompanyPatents = selection;
      }
    },

    // 渲染前置处理
    beforeRender(data) {
      if (data.entity.companyLabelsList) {
        let arr = [];
        data.entity.companyLabelsList.forEach(item => {
          //如果相等做操作
          item["labelId"] = item["labelId"] + "";
          arr.push(item.labelId);
        });
        this.companyLabelsList = arr;
      }
      if (data.entity.companyPatentsList) {
        this.companyPatentsList = data.entity.companyPatentsList;
      }

      return data;
    },
    /** 编辑 */
    edit(row) {
      this.reset();
      this.query = { id: row.id };
      this.urls.currUrl = "company/edit";
      this.getData();
      this.pageInfo.type = "edit";
      this.title = "编辑企业信息";
    },
    /** 新增 */
    add(row) {
      this.reset();
      this.urls.currUrl = "company/add";
      this.getData();
      this.pageInfo.type = "add";
      this.title = "新增企业";
    },
    /** 查看*/
    view(row) {
      this.reset();
      this.query = { id: row.id };
      this.urls.currUrl = "company/view";
      this.getData();
      this.pageInfo.type = "view";
      this.title = "企业详情";
    },
    /**取消按钮 */
    cancel() {
      this.open = false;
    },
    /**获取数据后弹框 */
    afterRender(data) {
      this.open = true;
    },

    afterSubmit(data) {
      this.open = false;
      this.$emit("ok");
    },

    // 表单重置
    reset() {
      this.form = {
        companyName: "",
        companyCode: "",
        registrationNumber: "",
        legalRepresentative: "",
        registeredCapital: "",
        companyType: "",
        businessScope: "",
        businessAdress: "",
        location: "",
        areaCode: "",
        areaName: "",
        contactPhone: "",
        email: "",
        website: "",
        taxRegistrationNumber: "",
        socialCreditCode: "",
        trademarkInfo: "",
        websiteRegistrationInfo: "",
        totalEmployees: null,
        softNum: null,
        patentNum: null,
        hisDevelop: "",
        lon: "",
        lati: "",
        logoPath: "",
        companyVideoPath: "",
        companyPicPath: "",
        companyIntroduction: "",
        companyCulture: "",
        sort: 0,
        establishDate: null,
        remark: "",
        companyLabelsList: [],
        companyPatentsList: []
      };
      this.resetForm("form");
    },
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
      }
    }
  },
  watch: {
    companyLabelsList(newval) {
      let arr = [];
      newval.forEach(item => {
        arr.push({
          labelId: item
        });
      });
      this.form.companyLabelsList = arr;
    }
  }
};
</script>

<style lang="less" scoped>
.del {
  color: red;
}
.formbtns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 60px;
  margin-top: 30px;
}
.zhshchq {
  margin-top: 20px;
}
</style>