<template>
  <uni-popup background-color="#fff" type="bottom"
    ref="openDeal"
    style="position: relative; z-index: 100"
  >
    <view style="padding: 32rpx;">
      <uni-forms style="width: 100%;"
        class="self-form"
        labelPosition="top"
        :model="formData"
        :rules="rules"
        ref="uForm"
        labelWidth="300"
      >
        <uni-forms-item label="实际解决时间" prop="actualSolveDate" required>
          <view
            class="picker-view"
            :class="{ selected: formData.actualSolveDate }"
          >
            <uni-datetime-picker
              type="date"
              :value="formData.actualSolveDate"
              start="2021-3-20"
              end="2030-6-20"
              @change="change"
            />
          </view>
        </uni-forms-item>
        <uni-forms-item label="经办人" prop="agentUserName" required>
          <view class="input-view">
            <uni-data-select
                style="width: 100%" 
                v-model="formData.agentUserId" 
                placeholder="请选择经办人" 
                :localdata="jingbrList1"
                @change="handleAgentChange"
              > 
              </uni-data-select>
          </view>
        </uni-forms-item>

        <uni-forms-item label="人员状态" prop="personStatus">
          <picker 
            @change="onpersonStatusChange" 
            :range="personStatusOptions.map(item => item.label)" 
            :value="getpersonStatusIndex(formData.personStatus)"
            mode="selector"
          >
            <view style="border: 1px solid #e4e4e4;width: 100%;box-sizing: border-box;padding: 0 20rpx;line-height: 64rpx;white-space: nowrap;text-overflow: ellipsis;flex-grow: 1;">{{ getpersonStatusLabel(formData.personStatus) || "请选择" }}</view>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="附件" prop="fileUrl">
          <ImageUpload
            :fileList="fileList"
            @update="changeFile"
            :maxCount="6"
          />
        </uni-forms-item>

        <uni-forms-item label="解决说明" prop="solveDesc" required>
          <view class="textarea-view">
            <textarea
              v-model="formData.solveDesc"
              placeholder="请输入解决说明"
              style="width: 100%;padding: 28rpx 36rpx;border: 1px solid #e4e4e4;padding: 10rpx;border-radius: 8rpx;font-size: 28rpx;color:#333333;height: 120rpx;"
            ></textarea>
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
    <view class="button-area">
      <view class="btn" @click="closeopenDeal">取消</view>
      <view
        class="btn reset"
        @click="
          formData.actualSolveDate = '';
          formData.solveDesc = '';
        "
        >重置</view
      >
      <view class="btn save" @click="finishJobRecommend(needsType)"
        >办结</view
      >
    </view>
  </uni-popup>
</template>

<script>
import ImageUpload from "@/packageRc/components/ImageUpload";
import { requirementCompletion } from "@/packageRc/apiRc/company/index";
import {getJbrInfo} from "@/packageRc/apiRc/personinfo/index"
export default {
  components: {
    ImageUpload,
  },
  data() {
    return {
      formData: {
        actualSolveDate: '',
        agentUserId: '',
        personStatus: '',
        fileUrl: '',
        solveDesc: ''
      },
      fileList: [],
      personStatusOptions: [],
      rules: {
        actualSolveDate: [
          {
            required: true,
            message: "请选择实际解决时间",
            trigger: ["blur", "change"],
          },
        ],
        agentUserName: [
          {
            required: true,
            message: "请填写经办人",
            trigger: ["blur", "change"],
          },
        ],
        personStatus: [
          {
            required: true,
            message: "请填写人员状态",
            trigger: ["blur", "change"],
          },
        ],
        solveDesc: [
          {
            required: true,
            message: "请填写解决说明",
            trigger: ["blur", "change"],
          },
        ],
      },
    }
  },
  created() {
    this.$getDict('qcjy_ryzt').then(res => {
      if (res.data && Array.isArray(res.data)) {
        this.personStatusOptions = res.data.map(item => ({
          value: item.dictValue,
          label: item.dictLabel
        }));
      }
    });
    getJbrInfo().then(res => {
      this.jingbrList1=res.map(ele => {
        return {
          value: ele.userId,
          text: ele.nickName
        }
      })
    })
  },
  methods: {
    init(formData) {
      this.formData = formData;
      this.$nextTick(() => {
        this.$refs.openDeal.open()
      })
    },
    // 获取帮扶内容标签
    getpersonStatusLabel(value) {
      let arr = this.personStatusOptions.filter(item => item.value == value)
      return arr.length ? arr[0].label : ''
    },
    getpersonStatusIndex(value) {
      if (!value) return 0;
      const index = this.personStatusOptions.findIndex(item => item.value === value);
      return index !== -1 ? index : 0;
    },
    // 处理人员状态选择变化
    onpersonStatusChange(e) {
      const index = e.detail.value;
      if (this.personStatusOptions && this.personStatusOptions[index]) {
        this.formData.personStatus = this.personStatusOptions[index].value;
      }
    },
    // 获取经办人名称
    getAgentUserName(userId) {
      const agent = this.jingbrList1.find(item => item.value === userId);
      return agent ? agent.nickName : '';
    },
    // 处理经办人选择变化
    handleAgentChange(value) {
      if (!value || !this.jingbrList1 || !this.jingbrList1.length) {
        this.formData.agentUserName = '';
        return;
      }
      const user = this.jingbrList1.find(item => item.value === value);
      if (user) {
        this.formData.agentUserName = user.nickName;
      } else {
        this.formData.agentUserName = '';
      }
    },
    // 办结按钮
    async finishJobRecommend() {
      uni.showLoading();
      try {
        // 先进行表单校验
        this.$refs.uForm.validate().then(res => {
          console.log('res', res);
          // 校验通过后再走后续逻辑
          const url = "/manage/personDemand/demandDone";
          requirementCompletion(url, this.formData).then(res => {
            if (res.code === 200) {
              uni.showToast({title: '办结成功', icon: 'none'});
              this.$refs.openDeal.close();
              this.$emit('finished')
            }
          })
        }).catch((error) => {
          console.log(error)
        })

      } catch (error) {
        let msg = '';
        if (error && error[0] && error[0].message) {
          msg = error[0].message;
        } else if (error && error.message) {
          msg = error.message;
        } else if (typeof error === 'string') {
          msg = error;
        } else {
          msg = '请检查必填项填写';
        }
        uni.showToast({title: msg, icon: 'none'});
      } finally {
        uni.hideLoading();
      }
    },
    changeFile(e) {
      // 清空当前的 fileUrl 数组
      this.formData.fileUrl = [];
      // 如果 e 有长度（即用户选择了文件）
      if (e.length) {
        // 遍历每个文件对象并获取其 url
        for (let data of e) {
          const url = data.data ? data.data.url : data.url;
          this.formData.fileUrl.push(url);
        }
      }
      this.formData.fileUrl = this.formData.fileUrl.join(',')
    },
    change(e) {
      this.formData.actualSolveDate = e
    },
  }
}
</script>

<style lang="scss" scoped>

.button-area {
  padding: 24rpx 32rpx 68rpx;
  background: #fff;
  display: flex;
  box-sizing: border-box;
  border-radius: 16px 16px 0px 0px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);

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

  .reset {
    background: #dce2e9;
  }

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