<template>
  <view class="page-container">
    <view class="work-order-form-content commonPageLRpadding">
      <up-form
          label-position="left"
          :model="workOrderForm"
          ref="workOrderFormRef"
          labelWidth="200rpx"
      >
        <!-- 1. 工单位置（地图选择）【赋值回显 + 完全禁止修改】 -->
        <up-form-item
            label="工单位置"
            prop="workLocation"
            border-bottom
            required
        >
          <up-input
              v-model="workOrderForm.workLocation"
              border="none"
              disabled

              placeholder="暂无工单位置"
          ></up-input>
        </up-form-item>

        <!-- 2. 工单名称（下拉框）【赋值回显 + 完全禁止修改】 -->
        <up-form-item
            label="工单名称"
            prop="orderName"
            border-bottom
            required
        >
          <up-input
              v-model="workOrderForm.orderName"
              disabled

              placeholder="暂无工单名称"
              border="none"
          ></up-input>
        </up-form-item>

        <!-- 3. 情况描述（文本域）【赋值回显 + 完全禁止修改】 -->
        <up-form-item
            label="情况描述"
            prop="problemDesc"
            required
        >
          <up-textarea
              v-model.trim="workOrderForm.problemDesc"
              count
              maxlength="200"
              rows="4"
              disabled
              disabled-color="#333333"
              placeholder="暂无情况描述"
          ></up-textarea>
        </up-form-item>

        <!-- 4. 问题照片【赋值回显 + 完全禁止修改/删除/新增】 -->
        <up-form-item label="问题照片" prop="problemImgs" required>
          <up-upload
              :file-list="problemImgs.imgList.value||[]"
              disabled
              multiple
              :width="70"
              :height="70"
              :max-count="problemImgs.uploadConfig.maxCount"
              :upload-text="problemImgs.uploadConfig.uploadText"
              :size-type="problemImgs.uploadConfig.sizeType"
          ></up-upload>
        </up-form-item>

        <!-- 派单情况分组（放在问题照片下方，增加间距） -->
        <view class="dispatch-group">
          <view class="dispatch-title">派单情况</view>

          <!-- 业务线单选框 -->
          <up-form-item
              label="业务线"
              prop="busiLineCn"
              border-bottom
              required
          >
            <up-radio-group
                v-model="workOrderForm.busiLineCn"
                placement="row"
                @change="handleBusiLineChange"
            >
              <up-radio
                  v-for="item in busiLineOptions"
                  :key="item.name"
                  :label="item.name"
                  :name="item.name"
              ></up-radio>
            </up-radio-group>
          </up-form-item>

          <!-- 道路名称（下拉框） -->
          <up-form-item
              label="道路名称"
              prop="roadName"
              border-bottom
              required
              @click="handleActionSheetOpen('roadName'); hideKeyboard()"
          >
            <up-input
                v-model="workOrderForm.roadName"
                readonly
                disabled-color="#ffffff"
                placeholder="请先选择工单位置"
                border="none"
            ></up-input>
            <template #right>
              <up-icon name="arrow-right" size="16" ></up-icon>
            </template>
          </up-form-item>

          <!-- 紧急程度选择 -->
          <up-form-item
              label="紧急程度"
              prop="pressingTypeName"
              border-bottom
              required
              @click="handleActionSheetOpen('pressingType'); hideKeyboard()"
          >
            <up-input
                v-model="workOrderForm.pressingTypeName"
                disabled
                disabled-color="#ffffff"
                placeholder="请选择紧急程度"
                border="none"
            ></up-input>
            <template #right>
              <up-icon name="arrow-right" size="16"></up-icon>
            </template>
          </up-form-item>
        </view>

        <!-- 5. 完成时间 -->
        <up-form-item
            label="希望完成时间"
            prop="expectedFinishDate"
            @click="show=true;hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.expectedFinishDate"
              border="none"
              readonly
              placeholder="点击选择时间"
          ></up-input>
          <template #right>
            <view v-if="workOrderForm.expectedFinishDate" @click.stop>
              <up-icon
                  name="close"
                  size="16"
                  @click.stop="clearExpectedFinishDate"
              ></up-icon>
            </view>
            <up-icon name="arrow-right" size="16" v-else></up-icon>
          </template>
        </up-form-item>
      </up-form>
    </view>

    <!-- 底部提交按钮 -->
    <view class="fixed-bottom-btn-wrap">
      <up-button
          type="primary"
          text="提交工单"
          @click="submitWorkOrder"
      ></up-button>
    </view>

    <!-- 合并后的通用下拉弹窗 -->
    <up-action-sheet
        :show="showActionSheet"
        :actions="currentActionSheetData.list"
        :title="currentActionSheetData.title"
        @close="handleActionSheetClose"
        @select="handleActionSheetSelect"
    ></up-action-sheet>

    <!-- 完成时间选择器 -->
    <up-datetime-picker
        :show="show"
        v-model="expectedFinishDate"
        mode="datetime"
        :min-date="new Date()"
        @cancel="show = false"
        @confirm="expectedFinishDateConfirm"
    ></up-datetime-picker>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onReady, onShow, onLoad } from '@dcloudio/uni-app';
import { useUploadImgs } from '@/common/utils/useUploadImgs'
import { getRoadListByLatLng } from '@/api/common'
import { daquUniversalApproval,  daquWorkorderCreate, qyUniversalApproval } from '@/api/regional-order-manage/regional-order-manage'
import { timeFormat } from '@/uni_modules/uview-plus'
import { nextStepMap } from '@/common/utils/common'
import { useUserStore } from '@/pinia/user';

// ========== 状态管理 ==========
const userStore = useUserStore();

// ========== 业务线相关状态 ==========
// 业务线映射表
const busiLineMap = ref({
  'yl': '园林',
  'sz': '市政',
  'wy': '物业',
  '园林': 'yl',
  '市政': 'sz',
  '物业': 'wy'
});

// 业务线选项列表
const busiLineOptions = ref([]);
const formatBusiLineOptions = () => {
  if (!userStore.userInfo?.user?.busiLine) {
    busiLineOptions.value = [];
    return;
  }
  const rawBusiLines = userStore.userInfo.user.busiLine.split(',');
  busiLineOptions.value = rawBusiLines.map(item => ({
    name: busiLineMap.value[item.trim()]
  }));
};

// 工具方法：通过中文名称获取对应的英文标识
const getBusiLineEnByCn = (cnName) => {
  return busiLineMap.value[cnName] || '';
};

// ========== 表单Ref ==========
const workOrderFormRef = ref(null)

// ========== 公共上传逻辑复用 ==========
const problemImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择问题照片',
  sizeType: ['compressed'],
  formRef: workOrderFormRef,
  fieldName: 'problemImgs'
})

if (!Array.isArray(problemImgs.rawImgList.value)) {
  problemImgs.rawImgList.value = [];
}

// ========== 页面状态 ==========
const showActionSheet = ref(false)
const currentActionSheetData = reactive({
  type: '',
  list: [],
  title: ''
})
const show = ref(false)
const expectedFinishDate = ref(Date.now())

// ========== 重新提交相关状态 ==========
const isRenew = ref(false);
const renewOrderData = ref(null);

// ========== 下拉列表数据 ==========
const roadNameList = ref([])
const orderNameList = ref([])
const pressingTypeList = ref([])

// ========== 工单表单数据 ==========
const workOrderForm = reactive({
  busiLineCn: '',
  roadId: 0,
  roadName: '',
  workLocation: '',
  orderName: '',
  pressingType: '',
  pressingTypeName: '',
  problemDesc: '',
  lat: 0,
  lon: 0,
  expectedFinishDate: '',
})

// ========== 表单校验规则 ==========
const workOrderFormRules = reactive({
  busiLineCn: [
    { type: 'string', required: true, message: '请选择业务线', trigger: ['change', 'blur'] }
  ],
  workLocation: [
    { type: 'string', required: true, message: '请选择工单位置', trigger: ['change', 'blur'] }
  ],
  roadName: [
    { type: 'string', required: true, message: '请选择道路名称', trigger: ['change', 'blur'] }
  ],
  orderName: [
    { type: 'string', required: true, message: '请选择工单名称', trigger: ['change', 'blur'] }
  ],
  pressingTypeName: [
    { type: 'string', required: true, message: '请选择紧急程度', trigger: ['change'] }
  ],
  problemDesc: [
    { type: 'string', required: true, message: '请输入情况描述', trigger: ['change', 'blur'] },
    { type: 'string', min: 3, max: 200, message: '情况描述需3-200字', trigger: ['change', 'blur'] }
  ],
  problemImgs: [problemImgs.imgValidateRule]
})

// ========== 生命周期 ==========
onLoad((options) => {
  // 初始化业务线选项
  formatBusiLineOptions();
  // 默认选中第一个业务线
  if (busiLineOptions.value.length > 0) {
    workOrderForm.busiLineCn = busiLineOptions.value[0].name;
  }

  // 兼容 重新提交的isRenew + 大区经理分配的纯tempKey 两种传参方式，统一赋值回显
  if ((options.isRenew == 1 && options.tempKey) || options.tempKey) {
    const tempKey = options.tempKey;
    try {
      const orderData = uni.getStorageSync(tempKey);
      console.log('orderData')
      console.log(orderData)
      if (orderData && typeof orderData === 'object') {
        renewOrderData.value = orderData;
        echoOrderData(renewOrderData.value);
      } else {
        uni.showToast({ title: '工单数据不存在，无法加载', icon: 'none' });
        setTimeout(() => uni.navigateBack(), 1000);
        return;
      }
    } catch (error) {
      console.error('读取工单数据失败：', error);
      uni.showToast({ title: '数据读取异常，无法加载', icon: 'none' });
      setTimeout(() => uni.navigateBack(), 1000);
      return;
    } finally {
      uni.removeStorageSync(tempKey);   // 调试完  打开
    }
  }
});

onReady(() => {
  if (workOrderFormRef.value) {
    workOrderFormRef.value.setRules(workOrderFormRules)
  }
  console.log('工单表单规则初始化完成')
})

onShow(() => {
  // 初始化工单名称列表
  orderNameList.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList('work_name'))
  // 初始化紧急程度列表
  pressingTypeList.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList('workorder_pressing_type'))
})

// ========== 核心方法 ==========
const echoOrderData = (orderItem) => {
  // 回显业务线
  if (orderItem.busiLine) {
    workOrderForm.busiLineCn = busiLineMap.value[orderItem.busiLine];
  }

  // 回显基础字段【核心：工单位置/工单名称/情况描述 赋值】
  workOrderForm.roadId = orderItem.roadId || 0;
  workOrderForm.roadName = orderItem.roadName || '';
  workOrderForm.workLocation = orderItem.lonLatAddress || orderItem.roadName || '';
  workOrderForm.orderName = orderItem.orderName || '';
  workOrderForm.pressingType = orderItem.pressingType || '';
  workOrderForm.pressingTypeName = uni.$dict.getDictLabel('workorder_pressing_type', orderItem.pressingType) || '';
  workOrderForm.problemDesc = orderItem.remark || '';
  workOrderForm.lat = orderItem.lat || 0;
  workOrderForm.lon = orderItem.lon || 0;
  workOrderForm.expectedFinishDate =  orderItem.expectedFinishDate ?timeFormat(orderItem.expectedFinishDate, 'yyyy-mm-dd hh:MM:ss')  : '';

  // 回显图片【核心：问题照片赋值】
  if (orderItem.problemsImgs && Array.isArray(orderItem.problemsImgs) && orderItem.problemsImgs.length > 0) {
    const imgList = orderItem.problemsImgs.map((imgUrl, index) => ({
      url: imgUrl,
      name: `renew_img_${index}`,
      status: 'success'
    }));
    problemImgs.imgList.value = imgList;
    problemImgs.rawImgList.value = imgList;
  }

  // 自动获取道路列表
  if (orderItem.lat && orderItem.lon) {
    getRoadListByBusiLine();
  }
};

// 业务线切换事件
const handleBusiLineChange = () => {
  workOrderForm.roadName = '';
  workOrderForm.roadId = 0;
  roadNameList.value = [];
  if (workOrderForm.workLocation) {
    getRoadListByBusiLine();
  }
};

// 获取道路列表（带业务线）
const getRoadListByBusiLine = async () => {
  if (!workOrderForm.lat || !workOrderForm.lon) {
    return;
  }
  const busiLineEn = getBusiLineEnByCn(workOrderForm.busiLineCn);
  if (!busiLineEn) {
    uni.showToast({ title: '业务线标识异常', icon: 'none' });
    return;
  }

  try {
    uni.showLoading({ title: '获取道路名称中...' });
    const roadRes = await getRoadListByLatLng({
      busiLine: busiLineEn,
      latitude: workOrderForm.lat,
      longitude: workOrderForm.lon
    });
    uni.hideLoading();
    if (Array.isArray(roadRes)) {
      roadNameList.value = roadRes.map((item) => ({
        name: item.roadName || '',
        code: item.roadCode || '',
        id: item.roadId || 0
      }));
    } else {
      roadNameList.value = [{ name: '未查询到道路名称', code: '', id: 0 }];
      uni.showToast({ title: '未查询到该位置的道路信息', icon: 'none' });
    }
  } catch (err) {
    uni.hideLoading();
    console.error('获取道路名称失败：', err);
    uni.showToast({ title: '获取道路名称失败，请重试', icon: 'none' });
    roadNameList.value = [{ name: '获取失败，请重新选择位置', code: '', id: 0 }];
  }
};

// ========== 通用弹窗方法 ==========
const handleActionSheetOpen = (type) => {
  if (type === 'roadName' && !workOrderForm.workLocation) {
    uni.showToast({ title: '请先选择工单位置', icon: 'none' })
    return
  }

  const configMap = {
    roadName: {
      title: '请选择道路名称',
      list: roadNameList.value
    },
    orderName: {
      title: '请选择工单名称',
      list: orderNameList.value
    },
    pressingType: {
      title: '请选择紧急程度',
      list: pressingTypeList.value
    }
  }

  currentActionSheetData.type = type
  currentActionSheetData.title = configMap[type].title
  currentActionSheetData.list = configMap[type].list
  showActionSheet.value = true
}

const handleActionSheetClose = () => {
  showActionSheet.value = false
  currentActionSheetData.type = ''
  currentActionSheetData.list = []
  currentActionSheetData.title = ''
}

const handleActionSheetSelect = (e) => {
  const { type } = currentActionSheetData
  switch (type) {
    case 'roadName':
      workOrderForm.roadName = e.name
      workOrderForm.roadId = e.code
      workOrderFormRef.value?.validateField('roadName')
      break
    case 'orderName':
      workOrderForm.orderName = e.name
      workOrderFormRef.value?.validateField('orderName')
      break
    case 'pressingType':
      workOrderForm.pressingType = e.value
      workOrderForm.pressingTypeName = e.name
      workOrderFormRef.value?.validateField('pressingTypeName')
      break
  }
  showActionSheet.value = false
}

const navigateBack = () => {
  uni.reLaunch({
    url: '/pages-sub/problem/work-order-manage/index',
    fail: () => {
      uni.navigateBack({ delta: 2 });
    }
  });
}

// 清除希望完成时间
const clearExpectedFinishDate = ()=> {
  workOrderForm.expectedFinishDate = ''
}

// 【注释无用方法：原选择工单位置方法，因为禁止修改，不需要点击触发】
const chooseWorkLocation = () => {}

// 完成时间确认
const expectedFinishDateConfirm = (e) => {
  workOrderForm.expectedFinishDate = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
  show.value = false
}

// 隐藏键盘
const hideKeyboard = () => {
  uni.hideKeyboard()
}

// 提交工单
const submitWorkOrder = async () => {
  try {
    await workOrderFormRef.value.validate()

    const busiLineEn = getBusiLineEnByCn(workOrderForm.busiLineCn);
    if (!busiLineEn) {
      uni.showToast({ title: '业务线选择异常，请重新选择', icon: 'none' });
      return;
    }

    const commonSubmitData = {
      roadId: workOrderForm.roadId,
      roadName: workOrderForm.roadName,
      problemsImgs: problemImgs.getSuccessImgUrls(),
      remark: workOrderForm.problemDesc.trim(),
      latLonType: 2,
      lat: workOrderForm.lat,
      lon: workOrderForm.lon,
      lonLatAddress: workOrderForm.workLocation,
      pressingType: workOrderForm.pressingType,
      orderName: workOrderForm.orderName,
      expectedFinishDate: workOrderForm.expectedFinishDate==""?"":new Date(workOrderForm.expectedFinishDate).getTime(),
      sourceId: 1,
      sourceName: workOrderForm.busiLineCn,
      busiLine: busiLineEn,

      workerDataId: renewOrderData.value.id,
      taskKey: renewOrderData.value.taskKey,
      taskId: renewOrderData.value.taskId,
      operateType: nextStepMap[renewOrderData.value.taskKey]?.operateTypePass || '',
      agree: 0,
      reason:  workOrderForm.problemDesc.trim(),
    }

    uni.showLoading({ title: '提交中...' })
    let res

    if (isRenew.value) {
      const renewSubmitData = {
        workerDataId: renewOrderData.value.id,
        taskKey: renewOrderData.value.taskKey,
        taskId: renewOrderData.value.taskId,
        operateType: nextStepMap[renewOrderData.value.taskKey]?.operateTypeRenew || '',
        agree: 0,
        reason:  workOrderForm.problemDesc.trim(),
        ...commonSubmitData
      }
      res = await qyUniversalApproval(renewSubmitData)
    } else {
      res = await qyUniversalApproval(commonSubmitData)
    }

    uni.hideLoading()
    uni.showToast({
      title: isRenew.value ? '重新提交成功' : '工单提交成功',
      icon: 'success',
      duration: 1000
    })

    setTimeout(() => {
      uni.reLaunch({
        url: '/pages-sub/problem/regional-order-manage/index'
      })
    }, 1000)
  } catch (error) {
    uni.hideLoading()

    if (!Array.isArray(error)) {
      console.error(isRenew.value ? '工单重新提交失败：' : '工单提交失败：', error)
      uni.showToast({
        title: isRenew.value ? error.msg : error.msg,
        icon: 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 全局页面样式
.page-container {
  min-height: 100vh;
  padding-bottom: 100rpx; // 给底部按钮留空间
}

// 工单表单内容容器
.work-order-form-content {
  background: #fff;
}

// 派单情况分组样式（核心：增加顶部间距）
.dispatch-group {
  padding-top: 20rpx; // 分组内顶部内边距，增强视觉区分
}

// 派单情况标题样式
.dispatch-title {
  font-size: 32rpx;
  font-weight: 600;
  color:$u-primary;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
}
</style>