<!-- 12月10号作备份 -->
<template>
  <el-drawer
    size="70%"
    append-to-body
    :title="title"
    :visible.sync="drawer"
    :wrapperClosable="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"

    @closed="closed"
  >
    <avue-form
      class="copy-form"
      :option="option"
      v-model="obj"
      ref="form"
      @submit="submit"
    >
      <!-- <template slot="userNature">
        <el-select v-model="obj.userNature">
          <el-option v-for="(item,index) in userNatureList" :key="index" :label="item.label" :value="item.value">{{item.label}}</el-option>
        </el-select>
      </template> -->
      <!-- <template slot-scope="{ disabled }" slot="wage">
        <el-input
          placeholder="请输入 参考工资"
          v-model="obj.wage"
          :disabled="disabled"
          class="input-with-select"
        >
          <el-select
            v-model="obj.wageUnitCategory"
            slot="append"
            placeholder="请选择单位"
            style="width: 100%"
            :disabled="disabled"
          >
            <template v-for="(item, key) in wageUnitCategory">
              <el-option
                v-if="!item.disable"
                :key="key"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </template>
          </el-select>
        </el-input>
      </template> -->

      <template slot="cityId" slot-scope="{ disabled }">
        <jl-cityLabel-cascader
          :disabled="disabled"
          filterable
          v-model="obj.cityId"
          placeholder="请选择 工作地址"
          :filterCity="['四川省', '德阳市']"
        ></jl-cityLabel-cascader>
      </template>

      <template slot="jobCompanyName" slot-scope="{row,disabled}">
        <!--        <el-select-->
        <!--          v-model="obj.jobCompanyName"-->
        <!--          filterable-->
        <!--          :remote="true"-->
        <!--          :remoteMethod="remoteMethod"-->
        <!--          @change="selectMissionCompany"-->
        <!--          :loading="missionCompanyLoad"-->
        <!--          placeholder="请选择"-->
        <!--        >-->
        <!--          <el-option-->
        <!--            v-for="item in options23"-->
        <!--            :key="item.label"-->
        <!--            :label="item.label"-->
        <!--            :value="item.label">-->
        <!--          </el-option>-->
        <!--        </el-select>-->
        <el-autocomplete
          style="'width：100%'"
          class="inline-input"
          v-model="obj.jobCompanyName"
          :fetch-suggestions="remoteMethod"
          placeholder="请输入用工单位"
          @select="selectMissionCompany"
        ></el-autocomplete>
      </template>
      <template slot="cityIdFrom" slot-scope="{ disabled }">
        <jl-cityLabel-cascader
          :disabled="disabled"
          filterable
          v-model="obj.cityId"
          placeholder="请选择 工作地址"
        ></jl-cityLabel-cascader>
      </template>
      <template slot-scope="{ row }" slot="wage">
        <el-input placeholder="请输入工资" type="number" v-model="obj.wage" class="input-with-select">
          <el-select v-model="obj.wageUnitCategory" slot="append" placeholder="请选择" @change="getMaxAndMin">
            <el-option :label="item.label" v-for="item in wageUnitCategory" :key="item.value"
                       :value="item.value"></el-option>
          </el-select>
        </el-input>
      </template>
      <template slot-scope="{ disabled }" slot="skillIds">
        <skill-select
          ref="skillSelect"
          :canSelect="!disabled"
          :selectedSkills="selectedSkills"
          :id="obj.worktypeIds"
          @add-skill="addSkill"
          @clear-validator="clearValidator('skillIds')"
        ></skill-select>
      </template>

      <template slot-scope="{ disabled }" slot="address">
        <!--        <select-map-->
        <!--          ref="selectMap"-->
        <!--          @addAddress="addAddress"-->
        <!--          @addressDel="addressDel"-->
        <!--          @input="inputAddress"-->
        <!--          :isCanEdit="!disabled"-->
        <!--          :lng="obj.lon"-->
        <!--          :lat="obj.lat"-->
        <!--          :address="obj.address"-->
        <!--          :type="type"-->
        <!--        ></select-map>-->
        <super-map-view
          ref="selectMap"
          @addAddress="addAddress"
          @addressDel="addressDel"
          @input="inputAddress"
          :isCanEdit="!disabled"
          :longitude="obj.lon"
          :latitude="obj.lat"
          :address="obj.address"
          :type="type"
          :open="true"
          :zoom="10"
          :min-zoom="10"
          :max-zoom="20"
          :flag-tip="false"
          placeholder="请输入详细地址"
        ></super-map-view>
      </template>
      <!-- 行业类型 -->
      <!-- <template slot="tradeId">
        <div class="tradeId">
            <el-autocomplete
              popper-class="my-autocomplete"
              v-model.trim="tradeState"
              :fetch-suggestions="querySearchAsync"
              placeholder="请选择行业类型"
              @select="handleSelect"
              show-word-limit
              ref="selectTradeId"
              >
              <template slot-scope="{ item }">
                <div class="name">{{item.value}}</div>
              </template>
            </el-autocomplete>
        </div>
      </template> -->
      <!-- 工种 -->
      <template slot="worktypeIds">
        <div class="tradeId">
          <el-autocomplete
            popper-class="my-autocomplete"
            v-model.trim="workTypeState"
            :fetch-suggestions="querySearchAsyncWorkType"
            placeholder="请选择工种"
            @select="handleSelectWorkType"
            show-word-limit
            :disabled="worktypeDisabled"
          >
            <!-- <el-button
            type="primary"
            :disabled = "workTypeBtnState"
            slot="suffix"
            @click="handleIconClickWorkType"
            size="mini"
            >+添加</el-button> -->
            <!-- <i class="el-icon-arrow-down" slot="suffix" @click="handleIconClickArrowDown"></i> -->
            <template slot-scope="{ item }">
              <div class="name">{{ item.value }}</div>
            </template>
          </el-autocomplete>
        </div>
      </template>
      <!--/自定义表单-->
      <template slot-scope="{ disabled }" slot="menuForm">
        <!--        <el-button type="primary" icon="el-icon-check" @click="submit">提交</el-button>-->
        <el-button type="warning" icon="el-icon-close" @click="closed">重置</el-button>
        <el-button
          icon="el-icon-circle-close"
          @click="drawer = false"
          :loading="disabled"
        >取消
        </el-button
        >
      </template>
    </avue-form>
  </el-drawer>
</template>

<script>
import {listCompany, jkWorksHistory, missionHistory} from "@/api/tenant/mission";
import {add, detail, update, tradeListAdd, getMounthDays, getDictionary} from "@/api/tenant/postzp";
import {getTrade, getWork, getSkillList, getWorkTypes} from "@/api/tenant/common";
import SkillSelect from "../Dialog/Skill";
import {isvalidatemobile} from "@/util/validate";
import {mapGetters} from "vuex";
import {
  wageUnitCategoryState,
  wageOptionsMonth,
  educationState,
  // genderState,
} from "@/common/dic";
// import { toCent } from "@/util/money";

const validateTel = (rule, value, callback) => {
  if (isvalidatemobile(value)[0]) {
    callback(new Error(isvalidatemobile(value)[1]));
  } else {
    callback();
  }
};

export default {
  name: 'work_copy_mission',
  data() {
    return {
      options23: [],
      missionCompanyLoad: false,
      skillArr: [],
      id: "",
      title: "",
      type: "",
      tradeBtnState: true,
      workTypeBtnState: true,
      worktypeDisabled: true,
      selectedSkillIds: [],
      selectedName: [],
      selectedSkills: [],
      tradeData: [],
      tradeNameAttr: [],
      tradeIdAttr: [],
      workData: [],
      workDataNameAttr: [],
      workDataIdAttr: [],
      skillIdAttr: [],
      obj: {
        wage: 0,
        wageUnitCategory: 3,
        sex: 0,
        ageDesc: "不限年龄",
        education: 7,
        experienceDesc: "不限经验",
        tradeId: null,
        tradeNames: null,
        userNature: "灵活用工",
        lat: 31.126855,
        lon: 104.397894
      },
      loading: false,
      drawer: false,
      wageUnitCategory: wageUnitCategoryState,
      restaurants: [],
      tradeState: '',
      workTypeState: '',
      timeout: null,
      days: null,//某个月份的天数
      endTimeFlag: true,
      stimeDate: null,
      workTypesNameList: [],
      wallMaxAndMin: [],
      dwlist: []
    };
  },
  components: {
    SkillSelect,
  },
  created() {
    this.$store.dispatch("InitArea");
    this.initData();
    this.getMaxAndMin()
    this.getHistroyCompanyList()
  },
  watch: {
    "obj.tradeId": function (val, oldval) {
      if (val) {
        getWork(val).then((res) => {
          this.workData = res;
          this.workDataNameAttr = res.map((ele) => {
            return ele.name
          })
          this.workDataIdAttr = res.map((ele) => {
            return ele.id
          })
          this.worktypeDisabled = false;
          if (val !== oldval && oldval) {
            this.obj.worktypeIds = "";
          }
        });
      } else {
        this.obj.worktypeIds = "";
      }
    },
    // "obj.wageUnitCategory": function () {
    //   if (this.$refs.form) this.$refs.form.$refs.form.validateField("wage");
    // },
    "stimeDate": function (n) {
      if (n) {
        getMounthDays(n).then(res => {
          this.days = res.data.data;
        })
      }
    },
    wallMaxAndMin(val) {
      if (!val.length) {
        return;
      }
      switch (true) {
        case this.obj.wage < Math.min(...val):
          this.obj.wage = Math.min(...val)
          return
        case this.obj.wage > Math.max(...val):
          this.obj.wage = Math.max(...val)
          return
      }
    }
  },
  computed: {
    ...mapGetters(["area", "userInfo"]),
    /*计算时间*/
    startDate() {
      const self = this;
      if (self.obj.stime) {
        return new Date(self.obj.stime);
      } else {
        return null;
      }
    },
    endDate() {
      const self = this;
      if (self.obj.etime) {
        return new Date(self.obj.etime);
      } else {
        return null;
      }
    },
    siginDate() {
      const self = this;
      if (self.obj.etimePub) {
        return new Date(self.obj.etimePub);
      } else {
        return null;
      }
    },
    startTime() {
      const self = this;
      if (self.startDate) {
        return self.startDate.getTime();
      } else {
        return null;
      }

    },
    endTime() {
      const self = this;
      if (self.endDate) {
        return self.endDate.getTime();
      } else {
        return null;
      }
    },
    siginTime() {
      const self = this;
      if (self.siginDate) {
        return self.siginDate.getTime();
      } else {
        return null;
      }
    },
    option() {
      const self = this;
      // var skill = function (rule, value, callback) {
      //   if (self.selectedSkills.length <= 0) {
      //     callback(new Error("请选择技能标签"));
      //   } else {
      //     callback();
      //   }
      // };
      // const wage = (rule, value, callback) => {
      //   if(value == ""){
      //     callback(
      //       new Error(
      //         "请填写参考工资"
      //       )
      //     );
      //   }else if (
      //     !/^([1-9]\d*|0)(\.\d{0,2})?$/.test(value) ||
      //     value <= 0 ||
      //     value > 99999
      //   ) {
      //     callback(
      //       new Error(
      //
      //       )
      //     );
      //   } else if (
      //     this.obj.wageUnitCategory === null ||
      //     this.obj.wageUnitCategory === undefined
      //   ) {
      //     callback(new Error("请选择单位"));
      //   } else {
      //     callback();
      //   }
      // };
      // const tradeId = (rule, value, callback) => {
      //   if(this.tradeState == null || this.tradeState == undefined || this.tradeState == ""){
      //     callback(
      //       new Error(
      //         "请选择行业类型"
      //       )
      //     )
      //   }else{
      //     if(!this.tradeBtnState){
      //       callback(
      //         new Error(
      //           "新增行业要添加后才能使用"
      //         )
      //       )
      //     }else{
      //         callback();
      //     }

      //   }
      // };
      // const workType = (rule, value, callback) => {
      //   if(this.workTypeState == null || this.workTypeState == undefined || this.workTypeState == ""){
      //     callback(
      //       new Error(
      //         "请选择工种"
      //       )
      //     )
      //   }else{
      //     if(!this.workTypeBtnState){
      //       callback(
      //         new Error(
      //           "新增工种要添加后才能使用"
      //         )
      //       )
      //     }else{
      //       callback();
      //     }
      //   }
      // }
      const validatePass = (rule, value, callback) => {
        let specialKey = "[`~#$^&*()=|{}\\[\\]<>/~#￥……&*（）——|{}【】《》%@‘”“']‘'";
        let flagValue = true;
        for (var i = 0; i < value.length; i++) {
          if (specialKey.indexOf(value.substr(i, 1)) != -1) {
            flagValue = false;
          }
        }
        if (flagValue) {
          callback();
        } else {
          callback(new Error('岗位名称不能输入特殊字符'));
        }


      };
      return {
        emptyBtn: false,
        menuPosition: "right",
        group: [
          {
            label: "岗位信息",
            prop: "missionInfo",
            arrow: false,
            column: [
              {
                label: "岗位名称",
                prop: "jobName",
                search: true,
                span: 24,
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入岗位名称",
                    trigger: "blur",
                  },
                  {
                    min: 2,
                    max: 30,
                    message: "长度在 2 到 30 个字",
                    trigger: "blur",
                  },
                  {validator: validatePass, trigger: 'blur'}
                ],
              },
              {
                label: "发布时间",
                prop: "stime",
                type: "date",
                placeholder: "请选择岗位开始日期",
                format: "yyyy-MM-dd",
                valueFormat: "yyyy-MM-dd 00:00:00",
                pickerOptions: {
                  disabledDate(time) {
                    const oneDay = 1000 * 60 * 60 * 24
                    return !(
                      time.getTime() + oneDay > Date.now() &&
                      (!self.endTime ||
                        (time.getTime() < self.endTime &&
                          time.getTime() > self.endTime - 2678400000)) &&
                      (!self.siginTime || time.getTime() > self.siginTime)
                    );
                  },
                },
                blur: ({value}) => {
                  self.obj.etime = '';
                  if (value) {
                    self.stimeDate = value.split(' ')[0]
                    self.endTimeFlag = false
                  } else {
                    self.endTimeFlag = true
                  }
                },

                rules: [
                  {
                    required: true,
                    message: "请选择岗位开始日期",
                    trigger: "blur",
                  },
                ],
                span: 12,
              },
              {
                label: "结束时间",
                prop: "etime",
                type: "date",
                placeholder: "请选择岗位结束日期",
                format: "yyyy-MM-dd",
                valueFormat: "yyyy-MM-dd 00:00:00",
                pickerOptions: {
                  disabledDate(time) {
                    if (!self.obj.stime) {
                      return true
                    }
                    if (self.days) {
                      // let mutiply=1000*60*60*24;
                      return !(time.getTime() > Date.now() && (!self.startTime || (time.getTime() > self.startTime)))
                    }
                  },
                },
                rules: [
                  {
                    required: true,
                    message: "请选择岗位结束日期",
                    trigger: "blur",
                  },
                ],
                span: 12,
              },
            ],
          },
          {
            label: "岗位要求",
            prop: "missionRequire",
            arrow: false,
            column: [
              {
                label: "招聘人数",
                prop: "peopleNum",
                type: "number",
                rules: [
                  {
                    required: true,
                    message: "请输入招聘人数",
                    trigger: "blur",
                  },
                  {
                    type: "number",
                    min: 1,
                    message: "招聘人数最少为1",
                    trigger: "blur",
                  },
                ],
                span: 12,
              },
              {
                label: "参考工资",
                prop: "wage",
                type: "select",
                formslot: true,
                labelslot: false,
                errorslot: false,
                // dicData: wageOptionsMonth,
                // rules: [
                //   {
                //     required: true,
                //     trigger: "blur",
                //   },
                // ],
                span: 12,
              },
              {
                label: "行业类型",
                prop: "tradeId",
                type: "select",
                dicData: this.tradeData,
                props: {
                  label: "name",
                  value: "id",
                },
                rules: [
                  {
                    required: true,
                    // validator: tradeId,
                    trigger: "blur",
                  },
                ],
                span: 12,
              },
              {
                label: "岗位工种",
                prop: "workSkills",
                type: "cascader",
                filterable: true,
                search: true,
                display: true,
                dicUrl: `/api/jobslink-api/tenant/worktypes/base/list?type=2`,
                dicFormatter: this.workSkillList,
                props: {
                  label: "name",
                  value: "id",
                  children: "child"
                },
                rules: [
                  {
                    required: true,
                    message: "请输入岗位名",
                    trigger: "blur",
                  },
                ],
                span: 12,
              },
              {
                label: "岗位描述",
                prop: "jobDescription",
                type: "textarea",
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入岗位描述",
                    trigger: "blur",
                  },
                  {
                    min: 30,
                    max: 200,
                    message: "长度在 30 到 200 个字",
                    trigger: "blur",
                  },
                ],
                placeholder: "请输入岗位描述，字数30-200字以内",
                span: 24,
                maxlength: 200,
                showWordLimit: true,
              },
            ],
          },
          {
            label: "人员要求",
            prop: "personRequire",
            arrow: false,
            column: [
              {
                label: "年龄要求",
                type: "select",
                prop: "ageDesc",
                dicData: [
                  {
                    label: "不限年龄",
                    value: "不限年龄",
                  },
                  {
                    label: "30以下",
                    value: "30以下",
                  },
                  {
                    label: "35以下",
                    value: "35以下",
                  },
                  {
                    label: "40以下",
                    value: "40以下",
                  },
                  {
                    label: "45以下",
                    value: "45以下",
                  },
                  {
                    label: "50以下",
                    value: "50以下",
                  },
                  {
                    label: "55以下",
                    value: "55以下",
                  },
                  {
                    label: "60以下",
                    value: "60以下",
                  },
                ],
                span: 8,
                clearable: false,
              },
              {
                label: "学历要求",
                type: "select",
                prop: "education",
                dicData: educationState,
                span: 8,
                clearable: false,
              },
              {
                label: "经验要求",
                type: "select",
                prop: "experienceDesc",
                dicData: [
                  {
                    label: "不限经验",
                    value: "不限经验",
                  },
                  {
                    label: "1年以下",
                    value: "1年以下",
                  },
                  {
                    label: "1~3年",
                    value: "1~3年",
                  },
                  {
                    label: "3~5年",
                    value: "3~5年",
                  },
                  {
                    label: "5~10年",
                    value: "5~10年",
                  },
                  {
                    label: "10年以上",
                    value: "10年以上",
                  },
                ],
                span: 8,
                clearable: false,
              },
            ],
          },
          {
            label: "用工单位信息",
            prop: "contactsRequire",
            arrow: false,
            column: [
              {
                label: "用工单位",
                prop: "jobCompanyName",
                rules: [
                  {
                    required: true,
                    message: "请输入用工单位",
                    trigger: "blur",
                  },
                ],
                formslot: true,
                span: 12,
              },
              {
                label: "单位信用代码",
                prop: "jobCompanyScale",
                // disabled: true,
                // rules: [
                //   {
                //     required: true,
                //     message: "请输入单位信用代码",
                //     trigger: "blur",
                //   },
                // ],
                span: 12,
              },
              {
                label: "所属行业",
                prop: "jobCompanyIndustry",
                // disabled: true,
                // rules: [
                //   {
                //     required: true,
                //     message: "请输入所属行业",
                //     trigger: "blur",
                //   },
                // ],
                span: 12,
              },
              {
                prop: "jobCompanyNature",
                label: "单位性质",
                type: 'select',
                // disabled: true,
                dicUrl: "/api/jobslink-api/system/dict-biz/dictionary?code=company_nature",
                props: {
                  label: "dictValue",
                  value: "dictKey",
                },
                // rules: [
                //   {
                //     required: true,
                //     message: "请输入单位性质",
                //     trigger: "blur",
                //   },
                // ],
                span: 12,
              },
              {
                label: "单位介绍",
                prop: "jobCompanyDescription",
                type: "textarea",
                rules: [
                  {
                    required: true,
                    message: "请输入单位介绍",
                    trigger: "blur",
                  },
                  {
                    min: 30,
                    max: 200,
                    message: "长度在 30 到 200 个字",
                    trigger: "blur",
                  },
                ],
                placeholder: "请输入单位介绍，字数30-200字以内",
                span: 24,
                maxlength: 200,
                showWordLimit: true,
              },
              {
                label: "联系人",
                prop: "callName",
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入联系人",
                    trigger: "blur",
                  },
                  {
                    min: 1,
                    max: 8,
                    message: "长度在 1 到 5 个字",
                    trigger: "blur",
                  },
                ],
                span: 8,
              },
              {
                label: "手机号",
                prop: "callTel",
                rules: [
                  {
                    required: true,
                    validator: validateTel,
                    trigger: "blur",
                  },
                ],
                span: 8,
              },
              {
                label: "座机",
                prop: "callNumber",
                span: 8,
              },
              {
                label: "工作地址",
                type: "input",
                prop: "cityId",
                rules: [
                  {
                    required: true,
                    message: "请选择工作地址",
                  },
                ],
                formslot: true,
                labelslot: false,
                errorslot: false,
                span: 24,
              },
              {
                label: "详细地址",
                prop: "address",
                formslot: true,
                labelslot: false,
                errorslot: false,
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入详细地址",
                    trigger: "blur",
                  },
                ],
                span: 24,
              },
            ],
          },
        ],
      };
    },
  },
  methods: {
    getHistroyCompanyList() {
      jkWorksHistory().then((res) => {
        const obj = res.data.data.map((item) => {
          return {
            ...item,
            label: item.jobCompanyName,
            value: item.jobCompanyName,
          }
        })
        this.options23 = obj
        this.dwlist = obj
      })
    },
    resetForm() {
      this.obj.jobName = ""
      this.obj.stime = ""
      this.obj.etime = ""
      this.obj.wage = ""
      this.obj.tradeId = ""
      this.obj.workSkills = true
      this.obj.jobDescription = ""
      this.obj.ageDesc = ""
      this.obj.education = ""
      this.obj.experienceDesc = ""
      // this.obj.jobCompanyName = ""
      // this.obj.jobCompanyIndustry = ""
      // this.obj.jobCompanyNature = ""
      // this.obj.jobCompanyDescription = ""
      // this.obj.callName = ""
      // this.obj.callTel = ""
      // this.obj.callNumber = ""
      // this.obj.cityId = ""
      // this.obj.address = ""
      this.obj.selectedSkills = []
      this.obj.$tradeId = ""
      this.obj.$workSkills = true
      this.obj.$ageDesc = ""
      this.obj.$education = ""
      this.obj.$experienceDesc = ""
      this.obj.$jobCompanyNature = ""
    },
    selectMissionCompany(value) {
      this.obj.jobCompanyScale = value.jobCompanyScale
      this.obj.jobCompanyIndustry = value.jobCompanyIndustry
      this.obj.jobCompanyNature = value.jobCompanyNature
      if (value.callTel) {
        this.obj.jobCompanyDescription = value.jobCompanyDescription
        this.obj.callName = value.callName
        this.obj.callTel = value.callTel
        this.obj.callNumber = value.callNumber
        this.obj.cityId = value.cityId
        this.obj.address = value.address
        this.obj.lon = value.lon
        this.obj.lat = value.lat
      }
    },
    async remoteMethod(query, cb) {
      if (!query) {
        this.options23 = this.dwlist
        cb(this.dwlist)
        return
      }
      this.missionCompanyLoad = true
      let resData = await listCompany({companyName: query})
      this.missionCompanyLoad = false
      if (resData.data.code === 200) {
        const op = resData.data.data.records.map((item) => ({
          label: item.jobCompanyName,
          ...item,
          value: item.jobCompanyName,
        }))
        this.options23 = op
        cb(op)
      }
    },
    wageBlur(e) {
      const value = e.target.value
      const val = this.wallMaxAndMin
      if (!val.length) {
        return;
      }
      switch (true) {
        case this.obj.wage < Math.min(...val):
          this.obj.wage = Math.min(...val)
          return
        case this.obj.wage > Math.max(...val):
          this.obj.wage = Math.max(...val)
          return
      }
    },
    async getMaxAndMin(id) {
      let params = {
        code: `wages_limit_${this.obj.wageUnitCategory}`
      }
      const arr = []
      const resData = await getDictionary(params)
      if (resData.data.code === 200) {
        resData.data.data.map((item) => {
          arr.push(Number(item.dictKey))
        })
        this.wallMaxAndMin = arr
      }
    },
    inputAddress(val) {
      this.obj.address = val;
    },
    workSkillList(res) {
      this.workTypesNameList = res.data
      const Deliver = (children, obj = {}) => {
        children.forEach((item) => {
          obj[item.id] = item.name
          if (item.child) {
            return Deliver(item.child, obj)
          }
        })
        return obj
      }
      this.workTypesNameObj = Deliver(res.data)
      return res.data
    },
    //过滤行业类型
    querySearchAsync(queryString, cb) {
      let results = [];
      let tradeNameState = this.tradeNameAttr.indexOf(queryString);
      if (tradeNameState == -1) {
        this.tradeBtnState = false;
      } else {
        this.tradeBtnState = true;
      }
      for (let i of this.tradeData) {
        i.value = i.name;
      }
      results = queryString ? this.tradeData.filter(this.createStateFilter(queryString)) : this.tradeData;
      cb(results);
    },
    //工种筛选
    querySearchAsyncWorkType(queryString, cb) {

      let results = [];
      let workDataNameState = this.workDataNameAttr.indexOf(queryString);
      if (workDataNameState == -1) {
        this.workTypeBtnState = false;
      } else {
        this.workTypeBtnState = true;
      }
      for (let i of this.workData) {
        i.value = i.name;
      }
      results = queryString ? this.workData.filter(this.createStateFilter(queryString)) : this.workData;
      cb(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    //行业类型
    handleSelect(item) {
      this.tradeBtnState = true;
      this.obj.tradeId = item.id;
      this.obj.tradeNames = item.name;
    },
    //工种
    handleSelectWorkType(item) {
      this.workTypeBtnState = true;
      this.obj.worktypeIds = item.id;
    },
    //点击行业类型添加按钮
    handleIconClick() {
      this.$message.closeAll();
      let nameState = this.tradeNameAttr.indexOf(this.tradeState)
      if (this.tradeState == "") {
        this.$message({
          type: "error",
          message: "请输入要添加的行业类型！",
        })
      } else if (nameState != -1) {
        this.$message({
          type: "error",
          message: "此行业类型已存在，请在列表中选择！",
        })
      } else {
        tradeListAdd(this.tradeState).then((res) => {
          if (res.data.code == 200) {
            this.obj.tradeId = res.data.data;
            this.$message({
              type: "success",
              message: res.data.msg,
            })
            this.tradeBtnState = true;
            this.initData();
            //this.$refs.form.clearValidate('tradeId');
            this.clearValidator('tradeId');
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
            })
          }
        });
      }

    },
    //点击工种添加按钮
    // handleIconClickWorkType() {
    //   this.$message.closeAll();
    //   let nameState = this.workDataNameAttr.indexOf(this.workTypeState)
    //   if(this.workTypeState == ""){
    //     this.$message({
    //       type: "error",
    //       message: "请输入要添加的工种！",
    //     })
    //   }else if(nameState != -1){
    //       this.$message({
    //         type: "error",
    //         message: "此工种已存在，请在列表中选择！",
    //     })
    //   }else{
    //     workListAdd(this.obj.tradeId,this.workTypeState).then((res) =>{
    //       if(res.data.code == 200){
    //         this.obj.worktypeIds = res.data.data;
    //         this.$message({
    //           type: "success",
    //           message: res.data.msg,
    //         })
    //         this.workTypeBtnState = true;
    //         this.clearValidator('worktypeIds');
    //         getWork(this.obj.tradeId).then((res) => {
    //           this.workData = res;
    //           this.workDataNameAttr = res.map((ele)=>{
    //             return ele.name
    //           })
    //         })
    //       }else{
    //         this.$message({
    //           type: "error",
    //           message: res.data.msg,
    //         })
    //       }
    //   });
    //   }

    // },
    //
    addressDel() {
      this.obj.address = "";
    },
    initData() {
      /*获取行业类型*/
      this.loading = true;
      getTrade(this.userInfo.company_id).then((res) => {
        this.tradeData = res;
        this.tradeNameAttr = res.map((ele) => {
          return ele.name
        })
        this.tradeIdAttr = res.map((ele) => {
          return ele.id
        })
        this.loading = false;
      });
      // 获取岗位名
      getWorkTypes(2).then(res => {
        console.log(res)
        this.skillArr = res.data.data;
      })
    },
    closed() {
      this.tradeState = "";
      this.workTypeState = "";
      this.$refs.form.init();
      this.$refs.form.resetForm();
      this.$refs.form.clearValidate();
      this.obj = {
        wageUnitCategory: 3,
        sex: 0,
        ageDesc: "不限年龄",
        education: 7,
        experienceDesc: "不限经验",
        userNature: "灵活用工",
        lat: 31.126855,
        lon: 104.397894
      };
    },
    /*地图*/
    addAddress(form) {
      this.obj.address = form.address + (form.title || "");
      this.obj.lat = form.lat;
      this.obj.lon = form.lng;
    },
    /*技能*/
    addSkill(arr) {
      if (arr.length) {
        this.selectedSkills = arr;
      } else {
        this.selectedSkills = [];
      }
    },
    submit(row, done) {
      if (this.$refs.selectMap.addressLocation == "") {
        return this.$message({
          type: "error",
          message: "请选择详细地址!",
        });
      }
      row.address = this.$refs.selectMap.addressLocation;
      // let ids = [];
      // let name = [];
      // this.selectedSkills.forEach((ele) => {
      //   ids.push(ele.id);
      //   name.push(ele.name);
      // });
      // let skillIds = ids.join(",");
      // let skillNames = name.join(",");
      if (this.skillArr && this.skillArr.length > 0) {
        this.skillArr.forEach(item => {
          if (item.id == row.workSkills[0]) {
            row.worktypeNames = item.name
            if (item.child && item.child.length > 0) {
              item.child.forEach(item2 => {
                if (item2.id == row.workSkills[1]) {
                  row.skillNames = item2.name;
                }
              })
            }
          }
        })
      }

      if (this.tradeData && this.tradeData.length > 0) {
        this.tradeData.forEach(item => {
          if (row.tradeId == item.id) {
            row.tradeNames = item.name
          }
        })
      }
      // const copy = JSON.parse(JSON.stringify(row))
      row.worktypeIds = row.workSkills.join(',')
      row.worktypeNames = row.workSkills.map((id) => this.workTypesNameObj[id]).join(',')
      row.workSkills = row.workSkills.join(',')
      console.log(row)
      // 修改原数据workSkills
      if (this.type === "add" || this.type === "copy") {
        this.$jlEvent("trialCheck")
          .then(() => {
            add({

              jobName: row.jobName,
              stime: row.stime,
              etime: row.etime,
              etimePub: row.etimePub,
              peopleNum: row.peopleNum,
              wage: row.wage,
              wageUnitCategory: row.wageUnitCategory,
              tradeId: row.tradeId,
              tradeNames: row.tradeNames,
              worktypeIds: row.worktypeIds,
              worktypeNames: row.worktypeNames,
              skillIds: row.workSkills[1],
              skillNames: row.skillNames,
              jobDescription: row.jobDescription,
              userNature: row.userNature,
              sex: row.sex,
              ageDesc: row.ageDesc,
              education: row.education,
              experienceDesc: row.experienceDesc,
              jobCompanyName: row.jobCompanyName,
              jobCompanyScale: row.jobCompanyScale,
              jobCompanyIndustry: row.jobCompanyIndustry,
              jobCompanyNature: row.jobCompanyNature,
              jobCompanyDescription: row.jobCompanyDescription,
              callName: row.callName,
              callTel: row.callTel,
              callNumber: row.callNumber,
              cityId: row.cityId.replace(/\s+/g, ""),
              address: row.address,
              lat: row.lat,
              lon: row.lon,
            }).then(
              () => {
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                done()
                this.$confirm('是否继续发布岗位？', {
                  confirmButtonText: "继 续",
                  cancelButtonText: "取 消",
                })
                  .then(_ => {
                    this.resetForm()
                  })
                  .catch(_ => {
                    this.drawer = false;
                    this.$emit("back");
                  });

              },
              (error) => {
                window.console.log(error);
                done();
              }
            );
          })
          .catch(() => {
            done();
          });
      } else if (this.type === "edit") {
        update({
          id: this.id,
          jobName: row.jobName,
          stime: row.stime,
          etime: row.etime,
          etimePub: row.etimePub,
          peopleNum: row.peopleNum,
          wage: row.wage,
          wageUnitCategory: row.wageUnitCategory,
          tradeId: row.tradeId,
          tradeNames: row.tradeNames,
          worktypeIds: row.worktypeIds,
          worktypeNames: row.worktypeNames,
          jobCompanyScale: row.jobCompanyScale,
          skillIds: row.workSkills[1],
          skillNames: row.skillNames,
          jobDescription: row.jobDescription,
          userNature: row.userNature,
          jobCompanyDescription: row.jobCompanyDescription,
          sex: row.sex,
          ageDesc: row.ageDesc,
          education: row.education,
          experienceDesc: row.experienceDesc,
          callName: row.callName,
          callTel: row.callTel,
          callNumber: row.callNumber,
          cityId: row.cityId.replace(/\s+/g, ""),
          address: row.address,
          lat: row.lat,
          lon: row.lon,
        }).then(
          () => {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done()
            this.$confirm('是否继续发布岗位？', {
              confirmButtonText: "继 续",
              cancelButtonText: "取 消",
            })
              .then(_ => {
                this.closed()
              })
              .catch(_ => {
                this.drawer = false;
                this.$emit("back");
              });
          },
          (error) => {
            window.console.log(error);
            done();
          }
        );
      }

    },
    clearValidator(val) {
      this.$refs.form.clearValidate(val);
    },
    onLoad(row, type) {
      this.type = type;
      this.id = row.id;
      this.$nextTick(() => {
        if (type != 'edit') {
          // getLastTaskInfo().then(res=>{
          //   const data=res.data.data;
          //   this.obj.callName=data.callName;
          //   this.obj.callTel=data.callTel;
          // })
        }

        if (type === "copy") {
          this.title = "复制岗位";
          detail(row.id).then((res) => {
            if (![1, 2].includes(res.wageUnitCategory)) {
              res.wageUnitCategory = null;
            }
            this.obj = res;
            this.obj.etimePub = "";
            this.obj.stime = "";
            this.obj.etime = "";
            this.drawer = true;
            let tradeIdState = this.tradeIdAttr.indexOf(this.obj.tradeId);
            //判断有无此行业
            if (tradeIdState == -1) {
              this.obj.tradeId = "";
              setTimeout(() => {
                this.$message({
                  type: "error",
                  message: "此岗位所包含行业已经不存在，请重新选择！",
                })
              }, 1000);
            } else {
              this.tradeState = this.obj.tradeNames;
              //判断有无此工种
              getWork(this.obj.tradeId).then((res) => {
                this.workData = res;
                this.workDataIdAttr = res.map((ele) => {
                  return ele.id
                })
                let workDataIdState = this.workDataIdAttr.indexOf(this.obj.worktypeIds);
                //判断有无此工种
                if (workDataIdState == -1) {
                  this.obj.worktypeIds = "";
                  setTimeout(() => {
                    this.$message({
                      type: "error",
                      message: "此岗位所包含工种已经不存在，请重新选择！",
                    })
                  }, 1000);
                } else {
                  this.workTypeState = this.obj.worktypeNames;
                  getSkillList(this.obj.worktypeIds).then((res) => {
                    this.skillIdAttr = res.data.data.records.map((ele) => {
                      return ele;
                    });
                    let newSelectedSkills = [];
                    this.skillIdAttr.forEach((val) => {
                      let selectedSkillsState = this.obj.selectedSkills.find(v => v.id == val.id);
                      if (selectedSkillsState) {
                        newSelectedSkills.push(val);
                      }
                    })
                    // 判断有无此技能
                    if (newSelectedSkills.length == 0) {
                      // setTimeout(()=>{
                      // this.$message({
                      //     type: "error",
                      //     message: "此岗位所包含技能已经不存在，请重新选择！",
                      //   })
                      // },1000);
                    } else {
                      this.selectedSkills = newSelectedSkills;
                    }
                  });
                }
              })
            }
          });
        } else if (type === "add") {
          this.title = "发布岗位";
          this.obj = {
            wageUnitCategory: 3,
            sex: 0,
            ageDesc: "不限年龄",
            education: 7,
            experienceDesc: "不限经验",
            userNature: "灵活用工"
          };
          this.selectedSkills = [];
          this.drawer = true;
          this.$nextTick(() => {
            this.$refs.form.clearValidate();
          })
          if (this.$refs.selectMap) {
            this.$refs.selectMap.geolocation();
          }
        } else if (type === "edit") {
          this.title = "编辑岗位";
          detail(row.id).then((res) => {
            if (res.cityId === -1) {
              res.cityId = ''
            }
            this.obj = res;
            // this.obj.workSkills = []
            // console.log(res.worktypeIds)
            this.obj.workSkills = !res.worktypeIds || res.worktypeIds.split(',')
            // this.obj.workSkills.push(res.worktypeIds)
            // this.obj.workSkills.push(res.skillIds)
            this.drawer = true;
            // let tradeIdState = this.tradeIdAttr.indexOf(this.obj.tradeId);
            //判断有无此行业
            // if(tradeIdState == -1){
            //   this.$message.closeAll();
            //   this.obj.tradeId = "";
            // }else{
            //   this.tradeState = this.obj.tradeNames;
            //   //判断有无此工种
            //   getWork(this.obj.tradeId).then((res) => {
            //     this.workData = res;
            //     this.workDataIdAttr = res.map((ele)=>{
            //       return ele.id
            //     })
            //     let workDataIdState = this.workDataIdAttr.indexOf(this.obj.worktypeIds);
            //     //判断有无此工种
            //     if(workDataIdState == -1){
            //       this.$message.closeAll();
            //       this.obj.worktypeIds = "";
            //     }else{
            //       this.workTypeState = this.obj.worktypeNames;
            //       getSkillList(this.obj.worktypeIds).then((res) => {
            //         this.skillIdAttr = res.data.data.records.map((ele)=>{
            //           return ele;
            //         });
            //         let newSelectedSkills = [];
            //         this.skillIdAttr.forEach((val) => {
            //           let selectedSkillsState = this.obj.selectedSkills.find(v => v.id == val.id);
            //           if(selectedSkillsState){
            //             newSelectedSkills.push(val);
            //           }
            //         })
            //         // 判断有无此技能
            //         if(newSelectedSkills.length == 0){
            //           setTimeout(()=>{
            //             this.$message.closeAll();
            //           this.$message({
            //               type: "error",
            //               message: "此岗位所包含技能已经不存在，请重新选择！",
            //             })
            //           },1000);
            //         }else{
            //           this.selectedSkills = newSelectedSkills;
            //         }
            //       });
            //       }
            //   })
            // }
          });
        }
      });
    },
  },
  mounted() {

  }
};
</script>
<style scoped>
.el-col,
.el-form-item {
  margin-bottom: 0px;
}
</style>
<style>
.input-with-select {
  width: 100%;
}

.copy-form .el-input-group__append {
  background-color: #fff;
}

.input-with-select .el-input-group__append .el-input__icon {
  display: none;
}

.input-with-select .el-input-group__append input {
  width: 105px;
  padding: 0;
  text-align: center;
}

.my-autocomplete li {
  line-height: normal;
  padding: 7px;
}

.my-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
}

.my-autocomplete li .addr {
  font-size: 12px;
  color: #b4b4b4;
}

.my-autocomplete li .highlighted .addr {
  color: #ddd;
}

.tradeId .el-autocomplete {
  width: 100%;
}

.tradeId .el-icon-plus:before {
  content: "\e6d9 添加行业类型";
  color: #606266;
}

.tradeId .el-input--small input {
  padding-right: 150px;
}
</style>
