<template>
  <div class="jobs">
    <section class="jobs-top">
      <div class="left">
        近两个月共有<span>{{ lastSecondNum }}</span
        >个在招职位
      </div>
      <div class="add-job" @click="add">新增职位</div>
    </section>
    <!-- <dl class="job-type">
      <dt>职位：</dt>
      <dd>
        <span class="active">全部</span>
        <span>服务员</span>
        <span>运营</span>
        <span>技术工</span>
      </dd>
    </dl> -->
    <section class="job-list">
      <Empty v-if="total < 1" text="暂无在招职位" />
      <div class="job-item" :class="{offline:item.status=='0'}" v-for="item in jobList" :key="item.id">
        <div class="left">
          <div class="name">{{ item.postName }}</div>
          <div class="details">
            <span class=""
              >{{ item.lowestSalary }}K-{{ item.highestSalary }}K</span
            >
            工作年限:{{ filterworkYear(item.workYear) }} /
            {{ filterEducations(item.educationBg) }}
          </div>
        </div>
        <div class="right">
          <div class="time">{{ item.updateTime || item.createTime }} 发布</div>
          <div class="tool">
            <span style="color: #4aad78" @click="goDetails(item.id)">查看</span>
            <span style="color: #4aad78" @click="edit(item)" v-if="item.status!='0'">修改</span>
            <span style="color: #ff4343" @click="del(item.id)">删除</span>
          </div>
        </div>
      </div>
    </section>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <div class="add-job-div">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          :close-on-click-modal="false"
        >
          <el-form-item
            label="职位名称"
            prop="postName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.postName"
              placeholder="请录入职位名称"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="工作经历（年）"
            prop="workYear"
            :label-width="formLabelWidth"
          >
            <!-- <el-input
              v-model="form.workYear"
              placeholder="请录入工作经验限制，输入0则为不限"
              autocomplete="off"
            ></el-input> -->
            <el-select v-model="form.workYear" placeholder="请选择">
              <el-option
                v-for="item in workYear"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="Number(item.dictValue)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="最低学历"
            prop="educationBg"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.educationBg" placeholder="请选择">
              <el-option
                v-for="item in jobForm.educations"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="Number(item.dictValue)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="职位描述"
            prop="description"
            :label-width="formLabelWidth"
          >
            <el-col :span="24">
              <text-edit
                placeholder="'111"
                :minHeight="jobForm.description.minHeight"
                :show-tool="0"
                v-model="form.description"
              ></text-edit>
            </el-col>
          </el-form-item>
          <el-form-item
            label="最低工资"
            prop="lowestSalary"
            :label-width="formLabelWidth"
          >
            <el-col :span="10">
              <el-select v-model="form.lowestSalary" placeholder="请选择">
                <el-option
                  v-for="item of 50"
                  :disabled="item >= form.highestSalary"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2">
              <div
                :style="{
                  width: '100%',
                  fontSize: '50px',
                  textAlign: 'center',
                }"
              >
                ~
              </div>
            </el-col>
            <el-col :span="10">
              <el-select v-model="form.highestSalary" placeholder="请选择">
                <el-option
                  v-for="item of 50"
                  :disabled="item <= form.lowestSalary"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2">
              <div
                :style="{
                  width: '100%',
                  fontSize: '40px',
                  paddingLeft: '3px',
                  fontWeight: 1,
                }"
              >
                K
              </div>
            </el-col>
          </el-form-item>
          <el-form-item label="工作地点" :label-width="formLabelWidth">
            <el-cascader
              filterable
              size="large"
              ref="addressSelect"
              :options="addressOptions"
              v-model="form.workPlace"
              :leafOnly="true"
              @change="handleChange"
            >
            </el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addcomPost,
  getComPostList,
  updateComPost,
  getDicData,
  dlComPost,
} from "@/utils/api";

import { regionDataPlus } from "element-china-area-data";
import textEdit from "./edit/index";
import Empty from "@/components/empty.vue";
export default {
  name: "",
  components: {
    textEdit,
    Empty,
  },
  props: {
    lastSecondNum: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      defaultArea: ["520000", "520100", "520102"],
      addressOptions: regionDataPlus,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postName: "",
      },
      jobForm: {
        educations: [],
        description: {
          minHeight: 150,
        },
      },
      workYear: [],
      jobList: [],
      total: 10,
      dialogTitle: "",
      dialogVisible: false,
      form: { workPlace: ["520000", "520100", "520102"] },
      formLabelWidth: "120px",
      rules: {
        postName: [
          { required: true, message: "请输入岗位名称", trigger: "blur" },
        ],
        workYear: [
          { required: true, message: "请输入工作年限", trigger: "blur" },
        ],
        educationBg: [
          { required: true, message: "请选择最低学历", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入岗位描述", trigger: "blur" },
        ],
        lowestSalary: [
          { required: true, message: "请输入最低工资(单位k)", trigger: "blur" },
        ],
        highestSalary: [
          { required: true, message: "请输入最高工资(单位k)", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    filterEducations() {
      return function (value) {
        let v = "";
        for (let i = 0; i < this.jobForm.educations.length; i++) {
          // console.log("value", value);
          // console.log("value", this.educations[i]);
          let item = this.jobForm.educations[i];
          if (value == item.dictValue) {
            v = item.dictLabel;
            break;
          }
        }
        return v;
      };
    },
    filterworkYear() {
      return function (value) {
        let v = "";
        for (let i = 0; i < this.workYear.length; i++) {
          // console.log("value", value);
          // console.log("value", this.educations[i]);
          let item = this.workYear[i];
          if (value == item.dictValue) {
            v = item.dictLabel;
            break;
          }
        }
        return v;
      };
    },
  },
  created() {
    this.handlegetComPostList();
    this.getEducations();
    this.initMap();
    this.getWorkYear();
  },
  methods: {
    getEducations() {
      let eduDictType = "degr_educ";
      getDicData(eduDictType).then((res) => {
        this.jobForm.educations = res.data;
      });
    },
    getWorkYear() {
      getDicData("work_year").then((res) => {
        this.workYear = res.data;
      });
    },

    //初始化省市的数据  修改“全部" 为 "全国" "全省" "全市"
    initMap() {
      let mapInitData = [];
      regionDataPlus.forEach(function (item, index) {
        if (item.label == "全部") {
          item.label = "全国";
          mapInitData.push(item);
        } else if (item.children) {
          let childerCity = [];
          item.children.forEach(function (cityItem, index) {
            if (cityItem.label == "全部") {
              cityItem.label = "全省";
              childerCity.push(cityItem);
            } else if (cityItem.children) {
              let childerArea = [];
              cityItem.children.forEach(function (areaItem, index) {
                if (areaItem.label == "全部") {
                  areaItem.label = "全市";
                  childerArea.push(areaItem);
                } else {
                  childerArea.push(areaItem);
                }
              });
              cityItem.children = childerArea;
              childerCity.push(cityItem);
            }
          });
          item.children = childerCity;
          mapInitData.push(item);
        }
      });
      this.addressOptions = mapInitData;
    },

    //修改以后数据的值
    handleChange(value) {
      if (value && value.length != 0) {
        let arr = this.$refs["addressSelect"].getCheckedNodes()[0].pathLabels;
        delete this.form["provinceId"];
        delete this.form["provinceName"];

        delete this.form["cityId"];
        delete this.form["cityName"];

        delete this.form["areaId"];
        delete this.form["areaName"];

        value.forEach((addId, index) => {
          if (!addId == "") {
            switch (index) {
              case 0:
                this.form.provinceId = addId;
                this.form.provinceName = arr[index];
                break;
              case 1:
                this.form.cityId = addId;
                this.form.cityName = arr[index];
                break;
              case 2:
                this.form.areaId = addId;
                this.form.areaName = arr[index];
                break;
            }
          }
        });
      }
      // console.log("this.form", this.form);
    },
    goDetails(id) {
      this.$router.push({ path: "/jobdetails", query: { id: id } });
    },
    cancel() {
      (this.form = { workPlace: this.defaultArea }),
        (this.dialogVisible = false);
    },
    add() {
      this.dialogTitle = "新增职位";
      this.dialogVisible = true;
    },
    edit(item) {
      this.dialogTitle = "编辑职位";
      this.dialogVisible = true;
      this.form = item;
      this.form.workPlace = ["520000", "520100", "520102"];
      this.form.workPlace[0] = item.provinceId.toString();
      this.form.workPlace[1] = item.cityId.toString();
      this.form.workPlace[2] = item.areaId.toString();
      console.log("item", item);
    },
    del(item) {
      this.$confirm("确认删除？")
        .then((res) => {
          dlComPost(item).then((res) => {
            this.handlegetComPostList();
            this.$emit("getTotal");
          });
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    handlegetComPostList() {
      getComPostList({ pageNum: 1, pageSize: 30, postName: "" })
        .then((res) => {
          console.log("getComPostList", res);
          this.jobList = res.data.rows;
          this.total = res.data.total;
        })
        .catch((err) => {
          this.$message.error(err.msg);
          // console.log("register err", err);
        });
    },
    submit() {
      console.log("this.form", this.form);
      if (this.dialogTitle == "新增职位") {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            addcomPost(this.form)
              .then((res) => {
                this.$message(res.msg);
                this.dialogVisible = false;
                this.handlegetComPostList();
              })
              .catch((err) => {
                this.$message.error(err.msg);
                // console.log("register err", err);
              });
          } else {
            this.$message.error("请填写必填项!");
            return false;
          }
        });
      } else if (this.dialogTitle == "编辑职位") {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            updateComPost(this.form)
              .then((res) => {
                // console.log("addcomPost", res);
                this.$message(res.msg);
                this.dialogVisible = false;
              })
              .catch((err) => {
                this.$message.error(err.msg);
                // console.log("register err", err);
              });
          } else {
            this.$message.error("请填写必填项!");
            return false;
          }
        });
      }

      // this.$confirm("确认更新？")
      //   .then((res) => {
      //     console.log("res", res);
      //     this.dialogVisible = false;
      //   })
      //   .catch((err) => {
      //     console.log("err", err);
      //   });
    },
  },
};
</script>

<style lang='scss' scoped>
//@import url()
@import "./jobs.scss";
.add-job-div {
  width: 76%;
  height: 70%;
  margin: auto;
  .dialog-footer {
    width: 180px;
    margin: auto;
  }
}
::v-deep {
  .el-cascader {
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
  .el-dialog {
    -moz-box-shadow: rgba(169, 169, 169, 0.6) 0px 0px 0px 20px; /* 老的 Firefox */
    box-shadow: rgba(169, 169, 169, 0.6) 0px 0px 0px 20px;
    border-radius: 0px;
    .el-dialog__header {
      background: rgb(0, 179, 138);
      span {
        color: white;
        font-size: 16px;
      }
      .el-dialog__headerbtn .el-dialog__close {
        color: white;
      }
    }
  }
}
</style>