<template>
  <div id="companyManagement">
    <search-box :formList="formList" @search="search" @init="init" />
    <table-list
      :tableSets="tableSet"
      :tableData="tableData"
      :navText="navText"
      @addClick="addClick"
      :loading="loading"
    >
      <template slot="customize">
        <el-button type="success" @click="customizeFunc" size="medium"
          >下载模板</el-button
        >
        <label for="mobles" class="el-button el-button--warning" style="margin-right:10px;padding:10px 20px;">导入</label
        ><input
          style="display: none"
          type="file"
          id="mobles"
          @change="importMoble"
        />
      </template>
      <template slot="btn" slot-scope="props">
        <el-button type="text" @click="addClick(props.scope.row, 2)"
          >详情</el-button
        >
        <el-button type="text" @click="addClick(props.scope.row, 0)"
          >修改</el-button
        >
        <el-button type="text" @click="del(props.scope.row)">删除</el-button>
      </template>
    </table-list>
    <pagination
      :total="total"
      :pageSize="pageSize"
      :currentPage="currentPage"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <el-dialog
      :visible.sync="dialogVisible"
      width="710px"
      :show-close="false"
      :before-close="close"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">
          {{ statusPop === 1 ? "添加" : statusPop === 0 ? "修改" : "详情" }}
        </div>
        <div class="rightBoxs">
          <img src="@/assets/images/Close@2x.png" alt="" @click="close" />
        </div>
      </div>
      <div>
        <el-form
          label-position="right"
          label-width="80px"
          :model="listData"
          :rules="rules"
          ref="listData"
        >
          <el-form-item
            v-for="(items, indexs) in listitem"
            :key="indexs"
            :label="items.label"
            :prop="items.prop"
          >
            <el-radio-group
              v-if="items.scope === 'radio'"
              v-model="listData[items.prop]"
            >
              <el-radio
                v-for="(item, index) in items.options"
                :key="index"
                :label="item.value"
                :disabled="statusPop === 2"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
            <div class="imgBox" v-else-if="items.scope === 'imgBox'">
              <label class="imgLabel" for="inputs">
                <div class="msPhoto" v-if="listData.logoUrl">
                  <img
                    :src="$methodsTools.splitImgHost(listData.logoUrl)"
                    alt="图片加载失败"
                  />
                </div>
                <div class="imgbbx" v-else>
                  <p style="margin-top: 49px">点击添加上传</p>
                  <i class="el-icon-plus"></i>
                  <p style="margin-bottom: 37px">
                    图片格式：.jpg/.png/jpeg/bmp
                  </p>
                </div>
                <input
                  :disabled="statusPop === 2"
                  id="inputs"
                  type="file"
                  ref="file"
                  style="display: none"
                  @change="getImgFile"
                />
              </label>
              <p>请上传300*300图片，以确保显示最佳效果</p>
            </div>
            <div class="imgBox" v-else-if="items.scope === 'imgBoxs'">
              <label class="imgLabel" for="inputsF">
                <div class="msPhoto" v-if="listData.licenseUrl">
                  <img
                    :src="$methodsTools.splitImgHost(listData.licenseUrl)"
                    alt="图片加载失败"
                  />
                </div>
                <div class="imgbbx" v-else>
                  <p style="margin-top: 49px">点击添加上传</p>
                  <i class="el-icon-plus"></i>
                  <p style="margin-bottom: 37px">
                    图片格式：.jpg/.png/jpeg/bmp
                  </p>
                </div>
                <input
                  :disabled="statusPop === 2"
                  id="inputsF"
                  type="file"
                  ref="file1"
                  style="display: none"
                  @change="getImgFileF"
                />
              </label>
              <p>请上传比例为16：9且小于2m的图片</p>
            </div>
            <el-input
              :disabled="statusPop === 2"
              v-else-if="items.scope === 'textarea'"
              type="textarea"
              :placeholder="items.placeholder"
              v-model="listData[items.prop]"
            ></el-input>
            <el-cascader
              :disabled="statusPop === 2"
              v-else-if="items.scope === 'selectBx'"
              v-model="listData[items.prop]"
              :options="items.options"
              :props="{
                emitPath: false,
                children: 'companyTradeSonVo',
                label: 'tradeName',
                value: 'tradeId',
              }"
            ></el-cascader>
            <el-select
              :placeholder="items.placeholder"
              :disabled="statusPop === 2"
              v-else-if="items.scope === 'select'"
              v-model="listData[items.prop]"
            >
              <el-option
                v-for="(item, index) in items.options"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <div v-else-if="items.scope === 'address'">
              <v-distpicker
                :disabled="statusPop === 2"
                @province="changeProvince"
                @city="changeCity"
                @area="changeArea"
                :province="listData[items.prop1]"
                :city="listData[items.prop2]"
                :area="listData[items.prop3]"
              ></v-distpicker>
            </div>
            <el-input
              :placeholder="items.placeholder"
              :disabled="statusPop === 2"
              v-else
              v-model="listData[items.prop]"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button
          type="primary"
          v-if="statusPop !== 2"
          @click="submit('listData')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import searchBox from "@/components/searchBox";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
import VDistpicker from "v-distpicker";
export default {
  components: { searchBox, tableList, pagination, VDistpicker },
  data() {
    return {
      loading: false, //当前表单加载是否加载动画
      navText: {
        title: "公司管理",
        index: 0,
        ch: "条",
        num: true,
        choice: false,
        addHide: false,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      //搜索
      formList: [
        {
          label: "公司名称",
          prop: "companyName",
          placeholder: "请输入公司名称",
        },
        {
          label: "公司类型",
          prop: "companyTypeId",
          placeholder: "请输入公司类型",
          scope: "select",
          options: [],
        },
        {
          label: "公司规模",
          prop: "companySizeId",
          placeholder: "请选择公司规模",
          scope: "select",
          options: [],
        },
      ],
      // 表单
      tableSet: [
        {
          label: "公司名称",
          prop: "companyName",
          hidden: true,
        },
        {
          label: "公司类型",
          prop: "companyType",
          hidden: true,
        },
        {
          label: "行业类别",
          prop: "industryTypeName",
          hidden: true,
        },
        {
          label: "公司规模",
          prop: "companySize",
          hidden: true,
        },
        {
          label: "公司介绍",
          prop: "companyIntroduce",
          hidden: true,
        },
        {
          label: "公司LOGO",
          prop: "logoUrl",
          hidden: true,
          width: "120px",
          scope: "img",
        },
        {
          label: "营业执照",
          prop: "licenseUrl",
          hidden: true,
          width: "120px",
          scope: "img",
        },
        {
          label: "统一社会信用代码",
          prop: "societyCode",
          hidden: true,
        },
        {
          label: "公司地址",
          prop1: "province",
          prop2: "city",
          prop3: "district",
          prop4: "address",
          hidden: true,
          width: "280px",
          scope: "address",
        },
        {
          label: "公司电话",
          prop: "companyPh",
          hidden: true,
        },
        {
          label: "联系人",
          prop: "linkMan",
          hidden: true,
        },
        {
          label: "公司邮箱",
          prop: "postBox",
          hidden: true,
          width: "140px",
        },
      ],
      tableData: [], //表单数据
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      // 弹窗字段
      listitem: [
        {
          label: "公司名称",
          prop: "companyName",
          placeholder: "请输入公司名称",
        },
        {
          label: "公司类型",
          prop: "companyTypeId",
          placeholder: "请选择公司类型",
          scope: "select",
          options: [],
        },
        {
          label: "公司规模",
          prop: "companySizeId",
          placeholder: "请选择公司规模",
          scope: "select",
          options: [],
        },
        {
          label: "行业类别",
          prop: "industryTypeId",
          placeholder: "请选择行业类别",
          scope: "selectBx",
          options: [],
        },
        {
          label: "公司介绍",
          prop: "companyIntroduce",
          placeholder: "请输入公司介绍",
          scope: "textarea",
        },
        {
          label: "公司logo",
          prop: "logoUrl",
          scope: "imgBox",
        },
        {
          label: "营业执照",
          prop: "licenseUrl",
          scope: "imgBoxs",
        },
        {
          label: "统一社会信用代码",
          prop: "societyCode",
          placeholder: "请输入统一社会信用代码",
        },
        {
          label: "公司地址",
          prop1: "province",
          prop2: "city",
          prop3: "district",
          scope: "address",
        },
        {
          label: "详细地址",
          prop: "address",
          placeholder: "请输入详细地址",
        },
        {
          label: "联系人",
          prop: "linkMan",
          placeholder: "请输入联系人",
        },
        {
          label: "公司电话",
          prop: "companyPh",
          placeholder: "请输入公司电话",
        },
        {
          label: "邮箱",
          prop: "postBox",
          placeholder: "请输入邮箱",
        },
      ],
      //   弹窗数据
      listData: {},
      statusPop: -1,
      dialogVisible: false,
      //表单验证
      rules: {
        companyName: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
        ],
        companyTypeId: [
          { required: true, message: "请选择公司类型", trigger: "change" },
        ],
        companySizeId: [
          { required: true, message: "请选择公司规模", trigger: "change" },
        ],
        industryTypeId: [
          { required: true, message: "请选择行业类别ID", trigger: "change" },
        ],
        companyIntroduce: [
          { required: true, message: "请输入公司介绍", trigger: "blur" },
        ],
        societyCode: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "blur",
          },
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        linkMan: [{ required: true, message: "请输入联系人", trigger: "blur" }],
        companyPh: [
          { required: true, message: "请输入公司电话", trigger: "blur" },
        ],
        postBox: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
      },
      psCity: {},
      beif: {},
    };
  },
  created() {
    this.companyGM();
    this.companyLX();
    this.getTrade();
  },
  mounted() {
    this.search();
  },
  methods: {
    getTrade() {
      var self = this;
      this.$api.recruitcompanyConlistTrade().then((res) => {
        console.log(res.rows);
        for (let i = 0; i < self.listitem.length; i++) {
          if (self.listitem[i].label === "行业类别") {
            self.listitem[i].options = res.rows;
          }
        }
      });
    },
    changeProvince(v) {
      this.psCity.province = v.value;
      this.psCity.city = "";
      this.psCity.district = "";
    },
    changeCity(v) {
      this.psCity.city = v.value;
      this.psCity.district = "";
    },
    changeArea(v) {
      this.psCity.district = v.value;
    },
    companyGM() {
      var arays = [];
      var newArrays = [];
      arays = this.$store.state.UserDict.filter((item, index) => {
        return item.dictType == "company_size";
      });
      arays.forEach((item, index) => {
        let arrayList = {
          label: item.dictLabel,
          value: item.dictCode,
        };
        newArrays.push(arrayList);
      });
      for (let i = 0; i < this.formList.length; i++) {
        if (this.formList[i].label === "公司规模") {
          this.formList[i].options = newArrays;
        }
      }
      for (let i = 0; i < this.listitem.length; i++) {
        if (this.listitem[i].label === "公司规模") {
          this.listitem[i].options = newArrays;
        }
      }
    },
    companyLX() {
      var arays = [];
      var newArrays = [];
      arays = this.$store.state.UserDict.filter((item, index) => {
        return item.dictType == "company_type";
      });
      arays.forEach((item, index) => {
        let arrayList = {
          label: item.dictLabel,
          value: item.dictCode,
        };
        newArrays.push(arrayList);
      });
      for (let i = 0; i < this.formList.length; i++) {
        if (this.formList[i].label === "公司类型") {
          this.formList[i].options = newArrays;
        }
      }
      for (let i = 0; i < this.listitem.length; i++) {
        if (this.listitem[i].label === "公司类型") {
          this.listitem[i].options = newArrays;
        }
      }
    },
    search(v) {
      this.loading = true;
      if (v === undefined) {
        v = {
          pageSize: this.pageSize,
          pageNum: this.currentPage,
        };
      }
      var data = {
        companyName: v.companyName,
        companySizeId: v.companySizeId,
        companyTypeId: v.companyTypeId,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      };
      this.$api.recruitcompanyConlist(data).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;
        this.navText.index = res.total;
      });
      this.loading = false;
    },
    init() {
      this.search();
    },
    del(v) {
      var self = this;
      this.$confirm("此操作将删除该公司, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var datas = {
            companyId: v.companyId,
            status: -1,
          };
          self.$api.editcompanyConedit(datas).then((res) => {
            if (res.code === 200) {
              self.$message.success("删除成功");
              self.search();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addClick(v, int) {
      if (v === undefined) {
        this.statusPop = 1;
        this.listData = {};
      } else {
        this.statusPop = int;
        this.$api.recruitcompanyCon(v.companyId).then((res) => {
          this.beif = JSON.parse(JSON.stringify(res.data));
          this.listData = res.data;
        });
      }
      this.dialogVisible = true;
    },
    submit(formName) {
      var self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            self.psCity.province === "" ||
            self.psCity.province === "省" ||
            self.psCity.province === undefined
          ) {
            self.$message.error("请选择省份");
            return;
          }
          if (
            self.psCity.city === "" ||
            self.psCity.city === "市" ||
            self.psCity.city === undefined
          ) {
            self.$message.error("请选择城市");
            return;
          }
          if (
            self.psCity.district === "" ||
            self.psCity.district === "区" ||
            self.psCity.district === undefined
          ) {
            self.$message.error("请选择区域");
            return;
          }
          if (!self.listData.logoUrl) {
            self.$message.error("请上传公司logo");
            return;
          }
          if (!self.listData.licenseUrl) {
            self.$message.error("请上传营业执照");
            return;
          }
          this.rulesTableSumbit();
        } else {
          return false;
        }
      });
    },
    async rulesTableSumbit() {
      var self = this;
      var dataLists = JSON.parse(JSON.stringify(this.listData));
      dataLists.province = self.psCity.province;
      dataLists.city = self.psCity.city;
      dataLists.district = self.psCity.district;
      if (this.statusPop === 1) {
        const awtimg1 = await this.imgUpload1(0);
        const awtimg2 = await this.imgUpload2(0);
        dataLists.logoUrl = awtimg1;
        dataLists.licenseUrl = awtimg2;
      }
      if (this.statusPop === 0) {
        if (this.listData.logoUrl !== this.beif.logoUrl) {
          const awtimg1 = await this.imgUpload1(0);
          dataLists.logoUrl = awtimg1;
        }
        if (this.listData.licenseUrl !== this.beif.licenseUrl) {
          const awtimg2 = await this.imgUpload2(0);
          dataLists.licenseUrl = awtimg2;
        }
      }
      if (this.statusPop === 1) {
        this.$api.addcompanyCon(dataLists).then((res) => {
          if (res.code === 200) {
            this.$message.success("新增成功");
            this.dialogVisible = false;
            this.search();
          }
        });
      }
      if (this.statusPop === 0) {
        this.$api.editcompanyConedit(dataLists).then((res) => {
          if (res.code === 200) {
            this.$message.success("修改成功");
            this.dialogVisible = false;
            this.search();
          }
        });
      }
      this.$refs["listData"].resetFields();
    },
    imgUpload1(int) {
      return new Promise((resolve, reject) => {
        this.$upload
          .upload(this.$refs.file[0].files[0], int)
          .then((res) => {
            this.$set(this.listData, "logoUrl", res);
            resolve(res);
          })
          .catch((err) => {
            this.$message.error("图片上传错误");
          });
      });
    },
    imgUpload2(int) {
      return new Promise((resolve, reject) => {
        this.$upload
          .upload(this.$refs.file1[0].files[0], int)
          .then((res) => {
            this.$set(this.listData, "licenseUrl", res);
            resolve(res);
          })
          .catch((err) => {
            this.$message.error("图片上传错误");
          });
      });
    },
    close() {
      if (this.statusPop === 2) {
        this.dialogVisible = false;
        return;
      }
      this.$confirm("是否关闭该窗口", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$refs["listData"].resetFields();
          this.dialogVisible = false;
        })
        .catch(() => {});
    },
    getImgFile() {
      var self = this;
      var file = this.$refs.file[0].files[0];

      if (file === undefined) {
        self.$set(self.listData, "logoUrl", "");
        return;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error("图片不得大于2MB");
        return;
      }
      var type = this.$refs.file[0].value.toLowerCase().split(".").splice(-1);
      if (
        type[0] != "jpg" &&
        type[0] != "png" &&
        type[0] != "jpeg" &&
        type[0] != "bmp"
      ) {
        this.$message.error("上传格式需为：.jpg/.png/.jpeg/bmp");
        this.$refs.file[0].value = "";
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (ev) {
        self.$set(self.listData, "logoUrl", ev.target.result);
      };
    },
    getImgFileF() {
      var self = this;
      var file = this.$refs.file1[0].files[0];

      if (file === undefined) {
        self.$set(self.listData, "licenseUrl", "");
        return;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error("图片不得大于2MB");
        return;
      }
      var type = this.$refs.file1[0].value.toLowerCase().split(".").splice(-1);
      if (
        type[0] != "jpg" &&
        type[0] != "png" &&
        type[0] != "jpeg" &&
        type[0] != "bmp"
      ) {
        this.$message.error("上传格式需为：.jpg/.png/.jpeg/bmp");
        this.$refs.file1[0].value = "";
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (ev) {
        self.$set(self.listData, "licenseUrl", ev.target.result);
      };
    },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.search();
    },
    customizeFunc() {
      let url =
        "https://file.xyyxt.net/oss/images/file/20210817/1629182141127_1059987581.xlsx";
      let link = document.createElement("a");
      let fileName = "导入模板" + ".xlsx";
      document.body.appendChild(link);
      link.href = url;
      link.dowmload = fileName;
      link.click();
      link.remove();
    },
    importMoble(e) {
      var self = this
      var file = e.target.files[0];
      let formData = new FormData();
      formData.append("file", file);
      this.$api.companyConimportExcel(formData).then((res) => {
        if(res.code === 200){
          self.$message.success("导入成功")
          self.search()
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-button {
  border-radius: 8px;
}
/deep/.el-dialog {
  border-radius: 8px;
  .el-dialog__header {
    padding: 0;
    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;
      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }
      .rightBoxs {
        display: flex;
        align-items: center;
        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }
  .el-dialog__footer {
    padding: 0;
    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
.imgBox {
  width: 300px;
  // height: 210px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  padding: 8px 8px 3px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    border: 1px dotted #e2e2e2;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;
    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 270px;
      img {
        max-width: 100%;
        max-height: 270px;
      }
    }
    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      i {
        font-weight: bold;
        margin: 14px 0;
        font-size: 24px;
      }
    }
  }
  p {
    margin: 5px 0px;
  }
  // .btnsUpload{
  //   display: block;
  //   padding: 10px 20px;
  //   font-size: 14px;
  //   border-radius: 8px;
  // }
}
</style>