<template>
  <el-dialog title="回访" append-to-body :visible.sync="dialogVisible" width="50%" :rules="rules"
    :before-close="handlePhoneClose">
    <el-form :model="phoneForm" label-position="left" label-width="100px">
      <!--      <div style="margin-bottom: 20px">-->
      <!--        <div class="phoneListStyle " v-for="phone in phoneList" :key="phone.PHONE">-->
      <!--          来源：<span style="color: #3a8ee6">{{ phone.DATASOURCE }} </span> &nbsp;&nbsp;&nbsp;电话号码： <span-->
      <!--          style="color: #3a8ee6">{{ phone.PHONE }}</span>-->
      <!--        </div>-->
      <!--      </div>-->
      <el-form-item label="联系方式">
        <el-checkbox-group v-model="phoneForm.list" :min="0" :max="1">
          <el-checkbox v-for="phone in phoneList" :label="phone" :key="phone">
            <span>{{ phone.DATASOURCE }}： </span> &nbsp;&nbsp;<span>{{ phone.PHONE }}</span>
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <div style="width: 100%; display: flex;flex-wrap: nowrap; justify-content: space-between;">
        <div style="flex: 1">
          <el-form-item label="人工录入">
            <el-input v-model="phoneForm.phone" :disabled="phoneForm.list.length" autocomplete="off"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-button type="danger" style="margin-left: 120px" :disabled="disablePhone" @click="updatePhoneInfo">
            更改联系方式
          </el-button>
        </div>
      </div>
      <el-form-item label="本人是否有就业意愿" label-width="180px" v-show="fieldVisibility.isWork">
        <el-radio-group v-model="phoneForm.isWork">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="本人是否需要服务" label-width="180px" v-show="fieldVisibility.isServe">
        <el-radio-group v-model="phoneForm.isServe">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="本人是否需要培训" label-width="180px" v-show="fieldVisibility.isTrain">
        <el-radio-group v-model="phoneForm.isTrain">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="fieldVisibility.isExitTitle" label-width="180px" v-show="fieldVisibility.isExit">
        <el-radio-group v-model="phoneForm.isExit">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否拒绝就业服务" label-width="180px" v-show="fieldVisibility.isReject">
        <el-radio-group v-model="phoneForm.isReject">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="拒绝服务有无正当理由" label-width="180px" v-show="fieldVisibility.isJustCase">
        <el-radio-group v-model="phoneForm.isJustCase">
          <el-radio :label="1">有</el-radio>
          <el-radio :label="0">无</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="fieldVisibility.exitReasonTitle" label-width="180px" v-show="fieldVisibility.exitReason">
        <el-autocomplete style="width: 100%" popper-class="my-autocomplete" v-model="phoneForm.exitReason"
          :fetch-suggestions="queryExitReason" placeholder="请输入内容" @select="handleSelect" :trigger-on-focus="true"
          clearable>
          <i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClick">
          </i>
          <template slot-scope="{ item }">
            <div class="name">{{ item }}</div>
          </template>
        </el-autocomplete>
      </el-form-item>

      <el-form-item label="期望薪资" v-show="fieldVisibility.salary">
        <el-select style="width: 100%" v-model="phoneForm.salary" placeholder="请选择 期望薪资">
          <el-option :label="item.value" :value="item.value" v-for="item in wageOptionsMonth"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="第一求职意愿" v-show="fieldVisibility.workSkillOne">
        <el-cascader v-model="phoneForm.workSkillOne" :options="workSkillsOptions"
          :props="{ label: 'name', value: 'name', children: 'child', emitPath: false }" filterable clearable
          placeholder="请选择第一求职意愿" style="width: 100%">
        </el-cascader>
      </el-form-item>
      <el-form-item label="第二求职意愿" v-show="fieldVisibility.workSkillTwo">
        <el-cascader v-model="phoneForm.workSkillTwo" :options="workSkillsOptions"
          :props="{ label: 'name', value: 'name', children: 'child', emitPath: false }" filterable clearable
          placeholder="请选择第二求职意愿" style="width: 100%">
        </el-cascader>
      </el-form-item>
      <el-form-item label="就业区县" v-show="fieldVisibility.workPlace">
        <el-select style="width: 100%" v-model="phoneForm.workPlace" placeholder="请选择就业区县">
          <el-option :label="item" :value="item" v-for="item in areaOptions"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拒绝服务理由" label-width="180px" v-show="fieldVisibility.rejectReason">
        <el-input v-model="phoneForm.rejectReason" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="文件佐证资料上传" label-width="180px" v-show="fieldVisibility.rejectResonUrl">
        <el-upload class="upload-demo" :action="uploadAction" :on-preview="handlePreview" :on-remove="handleRemove"
          :before-remove="beforeRemove" :on-success="handleSuccess" :on-error="handleError" :file-list="fileList"
          :limit="3" :on-exceed="handleExceed" :before-upload="beforeUpload" :http-request="customUpload" multiple>
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">支持pdf、docx、doc、xls、xlsx和图片格式，单个文件不超过10MB</div>
        </el-upload>
      </el-form-item>
    </el-form>


    <span slot="footer" class="dialog-footer">

      <el-button @click="handleManagement" v-show="fieldVisibility.regmanage">失业登记管理</el-button>
      <el-button @click="handleBasicUpdate" v-show="fieldVisibility.PersonalBaseInfo">个人基础信息修改</el-button>
      <el-button @click="handlePhoneClose">取 消</el-button>
      <el-button type="primary" @click="handelPhoneConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { phoneUpdate, serveUpdate } from "@/api/tenant/serve";
import { getWorkTypes } from "@/api/tenant/common";
import {
  wageOptionsMonth,
} from "@/common/dic";
import categoryVisibilityRules from './rulesForm'
import { putFileUpload } from '@/api/resource/oss.js'

export default {
  name: "FollowUpDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 传入的行数据
    item: {
      type: Object,
      default: () => null,
    },
    // 传入的当前所选分组ID
    serveId: {
      type: String,
      default: null,
    },
    phoneList: {
      type: Array,
      default: () => [],
    },
    workSkillsOptions: {
      type: Array,
      default: () => [],
    },
    areaOptions: {
      type: Array,
      default: () => [],
    },
    exitReasonOptions: {
      type: Array,
      default: () => [],
    },
    selectInfo: {
      type: Object,
      default: () => {
      },
    },
  },
  data() {
    return {
      wageOptionsMonth,
      phoneForm: {
        phone: '',
        list: [],
        isServe: '',
        isTrain: '',
        isWork: '',
        isReject: '',
        salary: '',
        workSkillOne: '',
        workSkillTwo: '',
        isExit: '',
        workPlace: '',
        exitReason: '',
        rejectReason: '',
        rejectResonUrl: '',
        isJustCase: '',
      },
      inputDisplays: [],
      // 文件上传相关数据
      fileList: [],
      uploadAction: '', // 上传地址
      uploadLoading: false,
      rules: {
        isServe: [
          { required: false, message: '请选择是否服务', trigger: 'change' }
        ],
        isTrain: [
          { required: false, message: '请选择是否培训', trigger: 'change' }
        ],
        isWork: [
          { required: false, message: '请选择是否有就业意愿', trigger: 'change' }
        ],
        salary: [
          { required: false, message: '请选择期望薪资', trigger: 'change' }
        ],
      },
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    },
    fieldVisibility() {
      let name = this.selectInfo ? this.selectInfo.name : null;
      if (name) name = name.trim()
      const strategyFn = categoryVisibilityRules[name] || categoryVisibilityRules.default;
      return strategyFn(this.phoneForm);
    },
    disablePhone() {
      const val = this.phoneForm.list[0] || null
      if (val && val.DATATYPE === '1') return true
      return false
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.setFormDefaults();
      } else {
        this.resetForm();
      }
    },
  },
  methods: {
    queryExitReason(queryString, cb) {
      var restaurants = this.exitReasonOptions;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      cb(results);
    },
    createFilter(queryString) {
      const lowerQuery = queryString.toLowerCase();
      return (restaurant) => {
        if (typeof restaurant !== 'string') {
          return false;
        }
        return restaurant.toLowerCase().includes(lowerQuery);
      };
    },
    handleSelect(item) {
      this.phoneForm.exitReason = item;
    },
    handleIconClick(ev) {
      // 点击图标时清空输入框
      this.phoneForm.exitReason = '';
      this.$nextTick(() => {
        // 获取输入框元素并聚焦
        const input = this.$el.querySelector('.my-autocomplete input');
        if (input) {
          input.focus();
        }
      });
    },

    // 文件上传相关方法
    // 自定义上传方法
    async customUpload(options) {
      const { file, onProgress, onSuccess, onError } = options;

      try {
        this.uploadLoading = true;

        // 使用 putFileUpload 函数进行上传
        const response = await putFileUpload(file, '3', (progressEvent) => {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress({ percent });
        });

        if (response.data && response.data.code === 200) {
          // 上传成功
          const fileUrl = response.data.msg; // 假设返回的是文件URL

          // 更新多文件URL（用逗号隔开）
          const currentUrls = this.phoneForm.rejectResonUrl ? this.phoneForm.rejectResonUrl.split(',').filter(url => url.trim()) : [];
          currentUrls.push(fileUrl);
          this.phoneForm.rejectResonUrl = currentUrls.join(',');

          // 添加到文件列表
          this.fileList.push({
            name: file.name,
            url: fileUrl,
            status: 'success'
          });

          onSuccess(response.data);
          this.$message.success('文件上传成功');
        } else {
          throw new Error('上传失败');
        }
      } catch (error) {
        console.error('文件上传失败:', error);
        onError(error);
        this.$message.error('文件上传失败: ' + (error.message || '未知错误'));
      } finally {
        this.uploadLoading = false;
      }
    },

    // 文件上传前验证
    beforeUpload(file) {
      const allowedTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'image/jpeg',
        'image/jpg',
        'image/png',
        'image/gif',
        'image/bmp'
      ];

      const isAllowedType = allowedTypes.includes(file.type);
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isAllowedType) {
        this.$message.error('只能上传pdf、doc、docx、xls、xlsx和图片格式的文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!');
        return false;
      }
      return true;
    },

    // 文件预览
    handlePreview(file) {
      if (file.url) {
        window.open(file.url, '_blank');
      }
    },

    // 文件移除
    handleRemove(file, fileList) {
      this.fileList = fileList;

      // 更新多文件URL（移除对应的URL）
      const currentUrls = this.phoneForm.rejectResonUrl ? this.phoneForm.rejectResonUrl.split(',').filter(url => url.trim()) : [];
      const updatedUrls = currentUrls.filter(url => url !== file.url);
      this.phoneForm.rejectResonUrl = updatedUrls.join(',');
    },

    // 移除前确认
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 上传成功
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },

    // 上传失败
    handleError(err, file, fileList) {
      this.fileList = fileList;
      this.$message.error('文件上传失败');
    },

    // 超出文件限制
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    async updatePhoneInfo() {
      let _this = this;
      let params = {
        idNumber: _this.item.idNumber,
        serveId: _this.serveId,
        serveUserId: _this.item.serveUserId,
      }
      // console.log(this.phoneForm.list)
      if (/^1[3-9]{1}\d{9}/.test(this.phoneForm.phone)) params.phone = this.phoneForm.phone;
      if (this.phoneForm.list.length) {
        const info = this.phoneForm.list[0]
        params.phone = info.PHONE
      }
      if (params.phone) {
        this.$confirm(`请同步更改省就业3.0系统中的人员联系方式`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async (res) => {
          const resData = await phoneUpdate(params)
          if (resData.data.code === 200) {
            _this.$message.success("更新成功");
            _this.handlePhoneClose();
            window.open('http://10.160.7.100:8000/jyback/template/general.html#/generalPage?_modulePartId_=1000076072', '_blank');
          }
        })


      } else {
        this.$message.error("请选择或输入用户手机号!");
      }
    },
    setFormDefaults() {
      if (this.item) {
        this.phoneForm.isServe = this.item.isServe || '';
        this.phoneForm.isTrain = this.item.isTrain || '';
        this.phoneForm.isWork = this.item.isWork || '';
        this.phoneForm.salary = this.item.isalary || '';
        this.phoneForm.workSkillOne = this.item.workSkillOne || '';
        this.phoneForm.workSkillTwo = this.item.workSkillTwo || '';
        this.phoneForm.workPlace = this.item.workPlace || '';
        this.phoneForm.exitReason = this.item.exitReason || '';
        this.phoneForm.isExit = this.item.isExit || '';
        this.phoneForm.isReject = this.item.isReject || '';
        this.phoneForm.rejectReason = this.item.rejectReason || '';
        this.phoneForm.rejectResonUrl = this.item.rejectResonUrl || '';
        this.phoneForm.isJustCase = this.item.isJustCase || '';

        // 初始化文件列表（如果已有文件URL）
        if (this.item.rejectResonUrl) {
          const urls = this.item.rejectResonUrl.split(',').filter(url => url.trim());
          this.fileList = urls.map((url, index) => ({
            name: `文件${index + 1}`,
            url: url,
            status: 'success'
          }));
        }
      }
    },
    handleBasicUpdate() {
      window.open('http://10.160.7.100:8000/jyback/template/general.html#/generalPage?_modulePartId_=1000076072', '_blank');
    },
    handleManagement() {
      window.open('http://10.160.7.100:8000/jyback/template/general.html#/generalPage?_modulePartId_=1000076072', '_blank');
    },
    handelJobIntention() {
      this.$message({ type: "info", message: "功能未配置" });
    },
    async handelPhoneConfirm() {
      const name = this.selectInfo ? this.selectInfo.name : null;
      let _this = this;
      let text = '请确认信息'
      // 麻烦的来了
      switch (true) {
        case name === '潜在就业困难人员' && this.phoneForm.isWork === 0:
          text = '请到 就业3.0 中注销该人员的失业登记信息'
          break
        case name === '潜在的就业困难退出人员' && this.phoneForm.isExit === 1:
          text = '请到 就业3.0 中注销该人员的就业登记困难人员登记信息'
          break
      }
      this.$confirm(text, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        let params = {
          idNumber: _this.item.idNumber,
          serveId: _this.serveId, // 使用 prop
          serveUserId: _this.item.serveUserId, // 使用 prop
          isServe: _this.phoneForm.isServe,
          isTrain: _this.phoneForm.isTrain,
          isExit: _this.phoneForm.isExit,
          isWork: _this.phoneForm.isWork,
          salary: _this.phoneForm.salary,
          workSkillOne: _this.phoneForm.workSkillOne,
          workSkillTwo: _this.phoneForm.workSkillTwo,
          workPlace: _this.phoneForm.workPlace,
          exitReason: _this.phoneForm.exitReason,
          isReject: _this.phoneForm.isReject,
          rejectReason: _this.phoneForm.rejectReason,
          rejectResonUrl: _this.phoneForm.rejectResonUrl,
          isJustCase: _this.phoneForm.isJustCase
        }
        let resData = await serveUpdate(params)
        if (resData.data.code === 200) {
          _this.$message.success("更新成功");
          switch (true) {
            case name === '潜在就业困难人员' && _this.phoneForm.isWork === 0:
              window.open('http://10.160.7.100:8000/jyback/template/general.html#/generalPage?_modulePartId_=1000076072', '_blank');
              break
            case name === '潜在的就业困难退出人员' && _this.phoneForm.isExit === 1:
              window.open('http://10.160.7.100:8000/jyback/template/general.html#/generalPage?_modulePartId_=1000241637', '_blank');
              break
          }
          _this.handlePhoneClose(); // 关闭弹窗
          _this.$emit('curdUpdate');

        }
      }).catch(() => {
      });
    },
    resetForm() {
      this.phoneForm.phone = '';
      this.phoneForm.list = [];
      this.phoneForm.isServe = '';
      this.phoneForm.isTrain = '';
      this.phoneForm.isWork = '';
      this.phoneForm.workPlace = '';
      this.phoneForm.exitReason = '';
      this.phoneForm.salary = '';
      this.phoneForm.isExit = '';
      this.phoneForm.workSkillOne = '';
      this.phoneForm.workSkillTwo = '';
      this.phoneForm.isReject = '';
      this.phoneList = [];
      this.phoneForm.rejectReason = '';
      this.phoneForm.rejectResonUrl = '';
      this.phoneForm.isJustCase = '';

      // 清理文件上传列表
      this.fileList = [];
      this.uploadLoading = false;
    },
    handlePhoneClose() {
      this.resetForm();
      this.dialogVisible = false; // 这将触发 .sync 更新
    },
  }
}
</script>

<style lang="scss" scoped>
.phoneListStyle {
  display: flex;
  flex-wrap: nowrap;
}
</style>
