<template>
  <view class="page">
    <u-navbar
      title="帮扶登记"
      :autoBack="true"
      bgColor="transparent"
      leftIconColor="#fff"
      :titleStyle="{ color: '#fff' }"
    ></u-navbar>
    <view class="input-outer-part">
      <scroll-view scroll-y="true" style="height: calc(100vh - 100px)">
        <view class="inner">
          <div class="self-form">
            <view class="inner-part">
              <div class="form-item required">
                <label class="form-label">被帮扶对象</label>
                <input
                  v-model="serviceForm.serviceObjectName"
                  style="border: none; width: 100%; padding: 10px 0;"
                  placeholder="请输入"
                  disabled
                />
              </div>
              
              <div class="form-item required">
                <label class="form-label">帮扶方式</label>
                <div class="form-value" @click="showPicker('demandType')" :class="{ noValue: !serviceForm.demandType }">
                  {{ getDemandTypeLabel(serviceForm.demandType) || "请选择" }}
                  <span class="arrow-down">▼</span>
                </div>
              </div>
              
              <div class="form-item required" v-if="serviceForm.demandType == '4' || serviceForm.demandType == '5'">
                <label class="form-label">帮扶时间</label>
                <div class="form-value" @click="showPicker('practicalSolutionTime')" :class="{ noValue: !serviceForm.practicalSolutionTime }">
                  {{ serviceForm.practicalSolutionTime || "请选择" }}
                  <span class="arrow-down">▼</span>
                </div>
              </div>
              
              <div class="form-item required" v-if="serviceForm.demandType == '4' || serviceForm.demandType == '5'">
                <label class="form-label">经办人</label>
                <div class="form-select-wrapper">
                  <el-select 
                    style="width: 100%" 
                    v-model="serviceForm.agentUserId" 
                    placeholder="请选择经办人" 
                    @change="handleAgentChange"
                  > 
                    <el-option 
                      v-for="item in jingbrList1" 
                      :key="item.userId" 
                      :label="item.nickName" 
                      :value="item.userId" 
                    ></el-option> 
                  </el-select>
                </div>
              </div>
              
              <div class="form-item required" v-if="serviceForm.demandType == '5'">
                <label class="form-label">电话沟通结果</label>
                <div class="form-value" @click="showPicker('dhgtjg')" :class="{ noValue: !serviceForm.dhgtjg }">
                  {{ getDhgtjgLabel(serviceForm.dhgtjg) || "请选择" }}
                  <span class="arrow-down">▼</span>
                </div>
              </div>
              
              <div class="form-item required" v-if="serviceForm.demandType == '4' || serviceForm.demandType == '5'">
                <label class="form-label">帮扶内容</label>
                <div class="form-value" @click="showPicker('serviceContent')" :class="{ noValue: !serviceForm.serviceContent }">
                  {{ getServiceContentLabel(serviceForm.serviceContent) || "请选择" }}
                  <span class="arrow-down">▼</span>
                </div>
              </div>
            </view>

            <view class="inner-part">
              <div class="form-item required" v-if="serviceForm.demandType == '4' || serviceForm.demandType == '5'">
                <label class="form-label">帮扶情况说明</label>
                <textarea
                  v-model="serviceForm.blqksm"
                  style="width: 100%; border: none; padding: 10px 0; min-height: 100px; resize: none;"
                  placeholder="请输入"
                ></textarea>
              </div>
              
     
       //     </view>

            <view class="inner-part" v-if="serviceForm.demandType == '4' || serviceForm.demandType == '5'">
              <div class="form-item">
                <label class="form-label">附件</label>
                <div style="width: 100%; padding: 10px 0;">
                  <button @click="triggerFileUpload" style="padding: 8px 16px; background: #f0f0f0; border: none; border-radius: 4px;">
                    上传附件 (最多6个)
                  </button>
                  <!-- 简单的文件列表显示 -->
                  <div v-if="serviceForm.fileUrl.length > 0" class="file-list">
                    <div v-for="(file, index) in serviceForm.fileUrl" :key="index" class="file-item">
                      {{ file.name }}
                      <span @click="removeFile(index)" style="margin-left: 10px; cursor: pointer; color: #ff4444;">删除</span>
                    </div>
                  </div>
                </div>
              </div>
            </view>
        </div>
        </view>
      </scroll-view>

      <view class="button-area">
        <view class="btn" @click="cancelPage">取消</view>
        <view class="btn save" @click="submitServiceForm">保存</view>
      </view>
    </view>
    
    <!-- 通用选择器 -->
    <div v-if="currentPicker" class="datetime-picker-overlay">
      <div class="datetime-picker">
        <div class="picker-header">
          <span @click="cancelPicker" style="padding: 10px;">取消</span>
          <span style="font-weight: bold;">{{ getPickerTitle(currentPicker) }}</span>
          <span @click="confirmPicker" style="padding: 10px; color: #007AFF;">确定</span>
        </div>
        <div class="picker-content">
          <div v-if="currentPicker === 'practicalSolutionTime'">
            <input 
              type="datetime-local" 
              v-model="manualDateTime" 
              style="width: 100%; padding: 15px; box-sizing: border-box;"
            />
          </div>
          <div v-else class="picker-options">
            <div 
              v-for="option in getPickerOptions(currentPicker)" 
              :key="option.value"
              @click="selectPickerOption(option.value)"
              :class="{ 'selected': selectedOption === option.value }"
            >
              {{ option.label }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </view>
</template>

<script>
import {getJbrInfo} from "../../api/personinfo/index"
export default {
  data() {
    return {
      serviceForm: {
        serviceObjectName: '',
        userId: '',
        demandType: '', // 帮扶方式
        practicalSolutionTime: '', // 帮扶时间
        agentUserId: '', // 经办人ID
        agentUserName: '', // 经办人名称
        dhgtjg: '', // 电话沟通结果
        serviceContent: '', // 帮扶内容
        blqksm: '', // 帮扶情况说明
        personStatus: '', // 人员状态
        fileUrl: [] // 附件
      },
      jingbrList1:[],
      currentPicker: null,
      selectedOption: '',
      manualDateTime: this.formatDateTime(new Date()),
      // 帮扶方式选项 (4: 上门服务, 5: 电话回访)
      demandTypeOptions: [
        { value: '4', label: '上门服务' },
        { value: '5', label: '电话回访' }
      ],
      // 经办人选项（模拟数据）
      jingbrList: [
        { userId: '1', nickName: '张三' },
        { userId: '2', nickName: '李四' },
        { userId: '3', nickName: '王五' }
      ],
      // 电话沟通结果选项
      dhgtjgOptions: [
        { value: '1', label: '已沟通' },
        { value: '2', label: '未接通' },
        { value: '3', label: '拒绝沟通' }
      ],
      // 帮扶内容选项
      serviceContentOptions: [
        { value: '1', label: '政策宣传' },
        { value: '2', label: '就业指导' },
        { value: '3', label: '技能培训' },
        { value: '4', label: '岗位推荐' },
        { value: '5', label: '其他' }
      ],
      // 人员状态选项
      personStatusOptions: [
        { value: '1', label: '已就业' },
        { value: '2', label: '未就业' },
        { value: '3', label: '灵活就业' }
      ]
    };
  },
async   created(){
this.getJbrInfo11()
const serviceContentOptions = await this.$getDictSelectOption('qcjy_fwnr');
  console.log('帮扶内容选项:', serviceContentOptions);
  this.serviceContentOptions = serviceContentOptions;
const serviceContentOptions1 = await this.$getDictSelectOption('qcjy_ryzt');
this.personStatusOptions=serviceContentOptions1
    },
  onLoad(options) {
    if (options.name) {
      this.serviceForm.serviceObjectName = options.name;
    }
    if (options.id) {
      this.serviceForm.userId = options.id;
    }
  },
  methods: {
   async getJbrInfo11(){
        const res=await getJbrInfo()
        this.jingbrList1=res
    },
    // 显示选择器
    showPicker(type) {
      this.currentPicker = type;
      if (type !== 'practicalSolutionTime') {
        this.selectedOption = this.serviceForm[type] || '';
      }
    },
    // 取消选择器
    cancelPicker() {
      this.currentPicker = null;
    },
    // 确认选择器
    confirmPicker() {
      if (this.currentPicker === 'practicalSolutionTime') {
        this.manualConfirmDate();
      } else {
        this.serviceForm[this.currentPicker] = this.selectedOption;
        // 特殊处理经办人，同时保存名称
        if (this.currentPicker === 'agentUserId') {
          const agent = this.jingbrList1.find(item => item.userId === this.selectedOption);
          this.serviceForm.agentUserName = agent ? agent.nickName : '';
        }
      }
      this.currentPicker = null;
    },
    // 选择选项
    selectPickerOption(value) {
      this.selectedOption = value;
    },
    // 获取选择器标题
    getPickerTitle(type) {
      const titles = {
        demandType: '选择帮扶方式',
        practicalSolutionTime: '选择帮扶时间',
        agentUserId: '选择经办人',
        dhgtjg: '选择电话沟通结果',
        serviceContent: '选择帮扶内容'
      };
      return titles[type] || '请选择';
    },
    // 获取选择器选项
    getPickerOptions(type) {
      const options = {
        demandType: this.demandTypeOptions || [],
        agentUserId: this.jingbrList1 && this.jingbrList1.length > 0 ? 
          this.jingbrList1.map(item => ({ value: item.userId, label: item.nickName })) : [],
        dhgtjg: this.dhgtjgOptions || [],
        serviceContent: this.serviceContentOptions || []
      };
      return options[type] || [];
    },
    // 获取帮扶方式标签
    getDemandTypeLabel(value) {
      const option = this.demandTypeOptions.find(item => item.value === value);
      return option ? option.label : '';
    },
    // 获取经办人名称
    getAgentUserName(userId) {
      const agent = this.jingbrList1.find(item => item.userId === userId);
      return agent ? agent.nickName : '';
    },
    // 处理经办人选择变化
    handleAgentChange(value) {
      if (!value || !this.jingbrList1 || !this.jingbrList1.length) {
        this.serviceForm.agentUserName = '';
        return;
      }
      const user = this.jingbrList1.find(item => item.userId === value);
      if (user) {
        this.serviceForm.agentUserName = user.nickName;
      } else {
        this.serviceForm.agentUserName = '';
      }
    },
    // 获取电话沟通结果标签
    getDhgtjgLabel(value) {
      const option = this.dhgtjgOptions.find(item => item.value === value);
      return option ? option.label : '';
    },
    // 获取帮扶内容标签
    getServiceContentLabel(value) {
      const option = this.serviceContentOptions.find(item => item.value === value);
      return option ? option.label : '';
    },
    // 格式化日期时间为YYYY-MM-DDTHH:MM格式（datetime-local输入框需要）
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day}T${hours}:${minutes}`;
    },
    
    // 手动确认日期选择
    manualConfirmDate() {
      // 将datetime-local格式转换为显示格式
      const date = new Date(this.manualDateTime);
      this.serviceForm.practicalSolutionTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    
    // 触发文件上传
    triggerFileUpload() {
      if (this.serviceForm.fileUrl.length < 6) {
        // 模拟添加文件
        const mockFiles = ['文档.pdf', '图片.jpg', '表格.xlsx', '报告.docx'];
        const randomFile = mockFiles[Math.floor(Math.random() * mockFiles.length)];
        this.serviceForm.fileUrl.push({
          name: randomFile,
          url: `mock-url/${Date.now()}/${randomFile}`
        });
      } else {
        uni.showToast({ title: '最多只能上传6个文件', icon: 'none' });
      }
    },
    
    // 删除文件
    removeFile(index) {
      this.serviceForm.fileUrl.splice(index, 1);
    },
    
    // 取消页面
    cancelPage() {
      uni.navigateBack();
    },
    
    // 验证表单
    validateForm() {
      if (!this.serviceForm.serviceObjectName) {
        uni.showToast({ title: '请填写被帮扶对象', icon: 'none' });
        return false;
      }
      if (!this.serviceForm.demandType) {
        uni.showToast({ title: '请选择帮扶方式', icon: 'none' });
        return false;
      }
      
      // 如果是上门服务或电话回访，需要验证更多字段
      if (this.serviceForm.demandType === '4' || this.serviceForm.demandType === '5') {
        if (!this.serviceForm.practicalSolutionTime) {
          uni.showToast({ title: '请选择帮扶时间', icon: 'none' });
          return false;
        }
        if (!this.serviceForm.agentUserId) {
          uni.showToast({ title: '请选择经办人', icon: 'none' });
          return false;
        }
        if (this.serviceForm.demandType === '5' && !this.serviceForm.dhgtjg) {
          uni.showToast({ title: '请选择电话沟通结果', icon: 'none' });
          return false;
        }
        if (!this.serviceForm.serviceContent) {
          uni.showToast({ title: '请选择帮扶内容', icon: 'none' });
          return false;
        }
        if (!this.serviceForm.blqksm) {
          uni.showToast({ title: '请填写帮扶情况说明', icon: 'none' });
          return false;
        }
        if (!this.serviceForm.personStatus) {
          uni.showToast({ title: '请选择人员状态', icon: 'none' });
          return false;
        }
      }
      
      return true;
    },
    
    // 提交表单
    async submitServiceForm() {
      try {
        // 验证表单
        if (!this.validateForm()) {
          return;
        }
        
        // 模拟加载状态
        uni.showLoading({ title: '保存中...' });
        
        // 准备提交数据
        const submitData = {
          ...this.serviceForm,
          // 格式化文件数据
          fileUrl: JSON.stringify(this.serviceForm.fileUrl)
        };
        
        // 打印提交数据
        console.log('提交数据:', submitData);
        
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        uni.showToast({ title: '保存成功', icon: 'success' });
        uni.navigateBack();
      } catch (error) {
        console.error(error);
        uni.showToast({ title: '保存失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  background-color: #eef1f5 !important;
  background-image: url("~@/packageRc/static/images/top.png");
  background-repeat: no-repeat;
  background-size: 100% auto;
}

.input-outer-part {
  background: #eef1f5;
  padding: 32rpx;
  padding-top: 100rpx; /* 增加顶部内边距，防止内容被遮挡 */
  position: relative;
  top: -80rpx;
  border-radius: 32rpx 32rpx 0 0;
}

.inner {
  .inner-part {
    background: #fff;
    padding: 0 32rpx;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
  }
}

.self-form {
  // 表单样式
}

/* 表单项目样式 */
.form-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

/* 选择器容器样式 */
.form-select-wrapper {
  flex: 1;
  padding: 5px 0;
}

.form-item.required .form-label::after {
  content: '*';
  color: #ff4444;
  margin-left: 4px;
}

.form-label {
  width: 110px;
  flex-shrink: 0;
  font-size: 14px;
  color: #333;
  padding: 10px 0;
}

.form-value {
  flex: 1;
  padding: 10px 0;
  font-size: 14px;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-value.noValue {
  color: #999;
}

.arrow-down {
  font-size: 12px;
  color: #A6A6A6;
}

.edit-icon {
  font-size: 14px;
  color: #A6A6A6;
}

.form-input-wrapper {
  flex: 1;
  position: relative;
}

.form-input-wrapper input {
  width: 100%;
  padding: 10px 0;
  border: none;
  outline: none;
  font-size: 14px;
}

.form-input-wrapper .edit-icon {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

/* 单选按钮样式 */
.radio-group {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  padding: 10px 0;
}

.radio-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
  margin-bottom: 10px;
  cursor: pointer;
}

.radio-item input[type="radio"] {
  margin-right: 6px;
}

.radio-label {
  font-size: 14px;
  color: #666;
}

/* 文件列表样式 */
.file-list {
  margin-top: 10px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
  color: #666;
}

/* 选择器样式 */
.datetime-picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.datetime-picker {
  background-color: #fff;
  border-radius: 8px;
  width: 80%;
  max-width: 400px;
  overflow: hidden;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;
}

.picker-content {
  max-height: 300px;
  overflow-y: auto;
}

.picker-options {
  padding: 10px 0;
}

.picker-options > div {
  padding: 15px 20px;
  font-size: 14px;
  color: #666;
}

.picker-options > div.selected {
  background-color: #f0f8ff;
  color: #1d64cf;
}

.noValue {
  color: #c0c4cc;
}

.button-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  background: #fff;
  display: flex;
  box-sizing: border-box;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .btn {
    line-height: 72rpx;
    width: 176rpx;
    margin-right: 16rpx;
    font-size: 28rpx;
    border: 1px solid #b8c5d4;
    color: #282828;
    text-align: center;
    border-radius: 8rpx;
  }

  .save {
    background: linear-gradient(103deg, #1d64cf 0%, #1590d4 99%);
    color: #fff;
    border: 0;
    flex-grow: 1;
  }
}
</style>
