<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
            @click="chooseWorkLocation(); hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.workLocation"
              border="none"
              readonly
              suffix-icon="map-fill"
              placeholder="点击选择工单位置"
          ></up-input>
        </up-form-item>

        <!-- 2. 问题类型（下拉框） -->
        <up-form-item
            label="问题类型"
            prop="orderName"
            border-bottom
            required
            @click="handleActionSheetOpen('orderName'); hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.orderName"
              disabled
              disabled-color="#ffffff"
              placeholder="请选择问题类型"
              border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-right" size="16"></up-icon>
          </template>
        </up-form-item>

        <!-- 3. 情况描述（文本域） -->
        <up-form-item
            label="情况描述"
            prop="problemDesc"
            required
        >
          <up-textarea
              placeholder="请输入情况描述（最多200字）"
              v-model.trim="workOrderForm.problemDesc"
              count
              maxlength="200"
              rows="4"
              @blur="() => workOrderFormRef.validateField('problemDesc')"
          ></up-textarea>
        </up-form-item>

        <!-- 4. 问题照片 -->
        <up-form-item label="问题照片" prop="problemImgs" required>
          <up-upload
              :file-list="problemImgs.imgList.value || []"
              @after-read="problemImgs.uploadImgs"
              @delete="problemImgs.deleteImg"
              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, nextTick } from 'vue'
import { onReady, onShow, onLoad, onBackPress } from '@dcloudio/uni-app';
import { useUploadImgs } from '@/common/utils/useUploadImgs'
import { getRoadListByLatLng } from '@/api/common'
import {
  daquUniversalApproval, qyUniversalApproval, qyWorkorderCreate,
  dcyUniversalApproval, daquWorkorderCreate, dcyWorkorderCreate
} 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 CONST = {
  // 字典编码
  DICT_ORDER_NAME: 'work_name',
  DICT_PRESSING_TYPE: 'workorder_pressing_type',
  // 上传配置
  UPLOAD_CONFIG: { maxCount: 3, uploadText: '选择问题照片', sizeType: ['compressed'] },
  // 路由地址
  PAGE_ORDER_LIST: '/pages-sub/problem/regional-order-manage/index',
  // 业务线映射
  BUSI_LINE_MAP: { yl: '园林', sz: '市政', wy: '物业', '园林': 'yl', '市政': 'sz', '物业': 'wy', 'zx': '秩序管理',
        'hj': '环境卫生', '秩序管理': 'zx',
        '环境卫生': 'hj', },
  // 角色标识
  ROLE: { MANAGER: 'regional_manager', INSPECTOR: 'Inspector_global', PATROL: 'patrol_global' }
}

// ========== 【全局实例 & 基础状态】 ==========
const userStore = useUserStore();
const USER_ROLES = userStore.userInfo?.roles || [];
const workOrderFormRef = ref(null);
const showActionSheet = ref(false);
const show = ref(false);
const expectedFinishDate = ref(Date.now());
const isRenew = ref(false);
const renewOrderData = ref(null);

// ========== 【下拉弹窗数据】 ==========
const currentActionSheetData = reactive({ type: '', list: [], title: '' });
const roadNameList = ref([]);
const orderNameList = ref([]);
const pressingTypeList = ref([]);
const busiLineOptions = ref([]);

// ========== 【上传逻辑复用】 ==========
const problemImgs = useUploadImgs({
  ...CONST.UPLOAD_CONFIG,
  formRef: workOrderFormRef,
  fieldName: 'problemImgs'
})
// 图片数组兜底，防止非数组报错
if (!Array.isArray(problemImgs.rawImgList.value)) problemImgs.rawImgList.value = [];

// ========== 【工单表单数据】 ==========
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]
})

// ========== 【工具方法封装】- 抽离通用逻辑，消灭重复代码 ==========
/**
 * 业务线中文转英文
 */
const busiLineCnToEn = (cn) => CONST.BUSI_LINE_MAP[cn] || '';
/**
 * 业务线英文转中文
 */
const busiLineEnToCn = (en) => CONST.BUSI_LINE_MAP[en] || '';
/**
 * 统一跳转返回工单列表页
 */
const toOrderListPage = () => uni.reLaunch({ url: CONST.PAGE_ORDER_LIST });
/**
 * 格式化时间戳 - 增加空值兜底
 */
const formatDate = (dateVal, fmt = 'yyyy-mm-dd hh:MM:ss') => dateVal ? timeFormat(dateVal, fmt) : '';
/**
 * 时间转时间戳 - 增加空值兜底
 */
const dateToTimestamp = (dateStr) => dateStr ? new Date(dateStr).getTime() : '';

// ========== 【生命周期】 ==========
onLoad((options) => {
  // 初始化工单线选项
  initBusiLineOptions();
  // 默认选中第一个业务线
  workOrderForm.busiLineCn = busiLineOptions.value[0]?.name || '';
  // 处理重新提交逻辑
  if (options.isRenew == 1 && options.tempKey) handleRenewOptions(options.tempKey);
});

onReady(() => {
  // 修复bug：nextTick确保表单ref一定挂载完成，再设置规则
  nextTick(() => {
    workOrderFormRef.value?.setRules(workOrderFormRules);
  });
});

onShow(() => {
  // 初始化下拉字典数据
  orderNameList.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList(CONST.DICT_ORDER_NAME));
  pressingTypeList.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList(CONST.DICT_PRESSING_TYPE));
});

// ========== 【核心业务方法】 ==========
/**
 * 初始化工单线选项
 */
const initBusiLineOptions = () => {
  const rawBusiLines = userStore.userInfo?.user?.busiLine?.split(',') || [];
  busiLineOptions.value = rawBusiLines.map(item => ({ name: busiLineEnToCn(item.trim()) }));
};

/**
 * 处理重新提交的参数和数据回显
 */
const handleRenewOptions = async (tempKey) => {
  isRenew.value = true;
  try {
    const orderData = uni.getStorageSync(tempKey);
    if (orderData && typeof orderData === 'object') {
      renewOrderData.value = orderData;
      echoOrderData(orderData);
    } else {
      uni.showToast({ title: '工单数据不存在，无法重新提交', icon: 'none' });
      setTimeout(toOrderListPage, 1000);
    }
  } catch (error) {
    console.error('读取工单数据失败：', error);
    uni.showToast({ title: '数据读取异常，无法重新提交', icon: 'none' });
    setTimeout(toOrderListPage, 1000);
  } finally {
    uni.removeStorageSync(tempKey);
  }
};

/**
 * 工单数据回显
 */
const echoOrderData = (orderItem) => {
  // 基础字段回显
  console.log(orderItem)
  console.log('123')
  workOrderForm.busiLineCn = busiLineEnToCn(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(CONST.DICT_PRESSING_TYPE, orderItem.pressingType) || '';
  workOrderForm.problemDesc = orderItem.remark || '';
  workOrderForm.lat = orderItem.lat || 0;
  workOrderForm.lon = orderItem.lon || 0;
  workOrderForm.expectedFinishDate = orderItem.expectedFinishDate?"":formatDate(orderItem.expectedFinishDate);

  // 图片回显 - 兼容异常格式
  if (Array.isArray(orderItem.problemsImgs) && orderItem.problemsImgs.length) {
    const imgList = orderItem.problemsImgs.map((url, idx) => ({ url, name: `renew_img_${idx}`, 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 = [];
  workOrderForm.workLocation && getRoadListByBusiLine();
};

/**
 * 根据坐标+业务线获取道路列表
 */
const getRoadListByBusiLine = async () => {
  if (!workOrderForm.lat || !workOrderForm.lon) return;
  const busiLineEn = busiLineCnToEn(workOrderForm.busiLineCn);
  if (!busiLineEn) return uni.showToast({ title: '业务线选择异常', icon: 'none' });

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

// ========== 【通用下拉弹窗方法】 ==========
const handleActionSheetOpen = (type) => {
  if (type === 'roadName' && !workOrderForm.workLocation) {
    return uni.showToast({ title: '请先选择工单位置', icon: 'none' });
  }
  const configMap = {
    roadName: { title: '请选择道路名称', list: roadNameList.value },
    orderName: { title: '请选择工单名称', list: orderNameList.value },
    pressingType: { title: '请选择紧急程度', list: pressingTypeList.value }
  };
  Object.assign(currentActionSheetData, configMap[type], { type });
  showActionSheet.value = true;
};

const handleActionSheetClose = () => {
  showActionSheet.value = false;
  Object.assign(currentActionSheetData, { type: '', list: [], title: '' });
};

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

// ========== 【页面交互方法】 ==========
/** 清除希望完成时间 */
const clearExpectedFinishDate = () => workOrderForm.expectedFinishDate = '';
/** 隐藏软键盘 */
const hideKeyboard = () => uni.hideKeyboard();
/** 时间选择确认 */
const expectedFinishDateConfirm = (e) => {
  workOrderForm.expectedFinishDate = formatDate(e.value);
  show.value = false;
};

/** 选择工单位置 */
const chooseWorkLocation = () => {
  uni.chooseLocation({
    success: async (res) => {
      workOrderForm.roadName = '';
      workOrderForm.roadId = 0;
      roadNameList.value = [];
      workOrderForm.workLocation = res.name;
      workOrderForm.lat = res.latitude;
      workOrderForm.lon = res.longitude;
      workOrderFormRef.value?.validateField(['workLocation', 'roadName']);
      await getRoadListByBusiLine();
    },
    fail: (err) => {
      console.error('选择位置失败：', err);
      const errMsg = err.errMsg.includes('auth deny') ? '请开启位置权限后重试' : '选择位置失败，请重试';
      uni.showToast({ title: errMsg, icon: 'none' });
    }
  })
};
// 新增页返回直接回列表页
onBackPress(() => {
  uni.redirectTo({
    url: '/pages-sub/problem/regional-order-manage/index'
  })
  return true;
})

// ========== 【封装：统一接口调用方法】 ==========
const callApiByRole = async (params, isRenewFlag) => {
  if (isRenewFlag) {
    if (USER_ROLES.includes(CONST.ROLE.MANAGER)) return await daquUniversalApproval(params);
    if (USER_ROLES.includes(CONST.ROLE.INSPECTOR)) return await dcyUniversalApproval(params);
    if (USER_ROLES.includes(CONST.ROLE.PATROL)) return await qyUniversalApproval(params);
  } else {
    if (USER_ROLES.includes(CONST.ROLE.MANAGER)) return await daquWorkorderCreate(params);
    if (USER_ROLES.includes(CONST.ROLE.INSPECTOR)) return await dcyWorkorderCreate(params);
    if (USER_ROLES.includes(CONST.ROLE.PATROL)) return await qyWorkorderCreate(params);
  }
};

// ========== 【核心：提交工单】 ==========
const submitWorkOrder = async () => {
  try {
    // 表单校验
    await workOrderFormRef.value.validate();
    const busiLineEn = busiLineCnToEn(workOrderForm.busiLineCn);
    if (!busiLineEn) return uni.showToast({ title: '业务线选择异常，请重新选择', icon: 'none' });

    // 组装公共提交参数
    const baseParams = {
      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: dateToTimestamp(workOrderForm.expectedFinishDate),
      sourceId: 1,
      sourceName: workOrderForm.busiLineCn,
      busiLine: busiLineEn
    };

    uni.showLoading({ title: '提交中...', mask: true });
    // 区分：重新提交 / 新增工单
    const submitParams = isRenew.value
        ? {
          workerDataId: renewOrderData.value.id,
          taskKey: renewOrderData.value.taskKey,
          taskId: renewOrderData.value.taskId,
          operateType: nextStepMap[renewOrderData.value.taskKey]?.operateTypeRenew || '',
          agree: 0,
          reason: workOrderForm.problemDesc.trim(),
          ...baseParams
        }
        : baseParams;

    // 统一调用接口
    await callApiByRole(submitParams, isRenew.value);

    // 提交成功处理
    uni.showToast({ title: isRenew.value ? '重新提交成功' : '工单提交成功', icon: 'success', duration: 1000 });
    setTimeout(toOrderListPage, 1000);
  } catch (error) {
    uni.hideLoading();
    if (!Array.isArray(error)) {
      console.error(isRenew.value ? '工单重新提交失败：' : '工单提交失败：', error);
      uni.showToast({ title: error.msg || '提交失败，请重试', icon: 'none', duration: 2000 });
    }
  }
}
</script>

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

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

// 派单情况分组样式
.dispatch-group {
  padding-top: 24rpx;
  margin-top: 8rpx;
  border-top: 1px solid #f5f5f5;

  .dispatch-title {
    font-size: 32rpx;
    font-weight: 600;
    color: $u-primary;
    margin-bottom: 20rpx;
    padding-left: 10rpx;
  }
}
</style>