<template>
  <view class="page-container">
    <!-- 核心：将所有 up-form-item 包裹在同一个 up-form 内 -->
    <view class="work-order-form-content commonPageLRpadding">
      <up-form
          label-position="left"
          :model="workOrderForm"
          ref="workOrderFormRef"
          labelWidth="160rpx"
      >

        <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>
        <!-- 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="roadName"
            border-bottom
            required
            @click="workOrderForm.workLocation ? (showRoadName = true, hideKeyboard()) : uni.showToast({title: '请先选择工单位置', icon: 'none'})"
        >
          <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>

        <!-- 3. 问题类型（下拉框） -->
        <up-form-item
            label="问题类型"
            prop="orderName"
            border-bottom
            required
            @click="showOrderName = true; 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>

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

        <!-- 问题照片 -->
        <up-form-item label="问题照片" prop="problemImgs" required>
          <up-upload
              :file-list="problemImgsList"
              @after-read="(event) => uploadImgs(event, 'problemImgsList')"
              @delete="(event) => deleteImg(event, 'problemImgsList')"
              multiple
              width="70"
              height="70"
              :max-count="3"
              upload-text="选择问题照片"
          ></up-upload>
        </up-form-item>

        <!-- 完成照片 -->
        <up-form-item label="完成照片" prop="completeImgs" required class="mt-20">
          <up-upload
              :file-list="completeImgsList"
              @after-read="(event) => uploadImgs(event, 'completeImgsList')"
              @delete="(event) => deleteImg(event, 'completeImgsList')"
              multiple
              width="70"
              height="70"
              :max-count="3"
              :sizeType="['compressed']"
              upload-text="选择完成照片"
          ></up-upload>
        </up-form-item>

        <!-- 处理结果（不必填） -->
        <up-form-item label="处理结果" prop="handleResult" class="mt-20">
          <up-textarea
              placeholder="请输入处理结果描述（最多200字，选填）"
              v-model.trim="workOrderForm.handleResult"
              count
              maxlength="200"
              rows="4"
              @blur="() => $refs.workOrderFormRef.validateField('handleResult')"
          ></up-textarea>
        </up-form-item>

      </up-form>
    </view>
    <!-- 底部提交按钮（移除loading和disabled属性） -->
    <view class="fixed-bottom-btn-wrap">
      <up-button
          type="primary"
          size="large"
          text="提交工单"
          @click="submitWorkOrder"
      ></up-button>
    </view>

    <!-- 道路名称下拉弹窗 -->
    <up-action-sheet
        :show="showRoadName"
        :actions="roadNameList"
        title="请选择道路名称"
        @close="showRoadName = false"
        @select="handleRoadNameSelect"
    ></up-action-sheet>

    <!-- 问题类型下拉弹窗 -->
    <up-action-sheet
        :show="showOrderName"
        :actions="orderNameList"
        title="请选择问题类型"
        @close="showOrderName = false"
        @select="handleOrderNameSelect"
    ></up-action-sheet>
  </view>
</template>

<script lang="ts">
import { getRoadListByLatLng } from '@/api/common'
import { uploadImages } from '@/common/utils/upload';
import { createQuick } from '@/api/quick-order/quick-order'
import { useUserStore } from '@/pinia/user';

export default {
  data() {
    return {
      // 业务线相关
      busiLineMap: {
        'yl': '园林',
        'sz': '市政',
        'wy': '物业',
        'zx': '秩序管理',
        'hj': '环境卫生',
        'yw': '常规运维',
        '园林': 'yl',
        '市政': 'sz',
        '物业': 'wy',
        '秩序管理': 'zx',
        '环境卫生': 'hj',
        '常规运维' : 'yw'
      },
      busiLineOptions: [], // 业务线选项列表
      // 问题照片列表
      problemImgsList: [],
      // 完成照片列表
      completeImgsList: [],
      // 弹窗显隐控制
      showRoadName: false,
      showOrderName: false,
      // 下拉列表数据
      roadNameList: [],
      orderNameList: [],
      // 工单表单数据
      workOrderForm: {
        busiLineCn: '', // 业务线中文名称
        roadId: 0,                     // 道路ID
        roadName: '',                  // 道路名称
        workLocation: '',              // 工单位置
        orderName: '',                 // 问题类型
        problemDesc: '',               // 情况描述
        handleResult: '',              // 处理结果描述（不必填）
        lat: 0,                        // 纬度
        lon: 0                         // 经度
      },
      // 表单校验规则
      workOrderFormRules: {
        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'] }
        ],
        problemDesc: [
          { type: 'string', required: true, message: '请输入情况描述', trigger: ['change', 'blur'] },
          { type: 'string', min: 3, max: 200, message: '情况描述需3-200字', trigger: ['change', 'blur'] }
        ],
        problemImgs: [
          {
            required: true,
            message: '请上传问题照片',
            trigger: 'change',
            validator: (rule, value, callback) => {
              const hasSuccessImg = this.problemImgsList.some(item => item.status === 'success')
              hasSuccessImg ? callback() : callback(new Error('请上传至少1张问题照片'))
            }
          }
        ],
        completeImgs: [
          {
            required: true,
            message: '请上传完成照片',
            trigger: 'change',
            validator: (rule, value, callback) => {
              const hasSuccessImg = this.completeImgsList.some(item => item.status === 'success')
              hasSuccessImg ? callback() : callback(new Error('请上传至少1张完成照片'))
            }
          }
        ]
      }
    }
  },
  onLoad() {
    // 初始化业务线选项
    this.initBusiLineOptions();
    // 默认选中第一个业务线
    if (this.busiLineOptions && this.busiLineOptions.length > 0) {
      this.workOrderForm.busiLineCn = this.busiLineOptions[0].name;
      console.log('默认选中业务线：', this.workOrderForm.busiLineCn);
    }
  },
  onReady() {
    // 设置表单校验规则
    this.$refs.workOrderFormRef.setRules(this.workOrderFormRules);
    console.log('工单表单规则初始化完成');
  },
  onShow() {
    this.orderNameList = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList('work_name'));
    console.log('问题类型列表：', this.orderNameList);
  },
  methods: {
    // 初始化业务线选项
    initBusiLineOptions() {
      // 获取pinia中的用户信息
      const userStore = useUserStore();
      if (userStore.userInfo?.user?.busiLine) {
        const rawBusiLines = userStore.userInfo.user.busiLine.split(',');
        // 生成中文名称列表
        this.busiLineOptions = rawBusiLines.map(item => ({
          name: this.busiLineMap[item.trim()] // name=中文名称（园林/市政/物业）
        }));
      }
      console.log('业务线选项：', this.busiLineOptions);
    },
    // 工具方法：通过中文名称获取对应的英文标识
    getBusiLineEnByCn(cnName) {
      return this.busiLineMap[cnName] || '';
    },
    // 业务线切换事件
    handleBusiLineChange() {
      // 清空道路信息
      this.workOrderForm.roadName = '';
      this.workOrderForm.roadId = 0;
      this.roadNameList = [];
      // 若已选择位置，重新请求对应业务线的道路列表
      if (this.workOrderForm.workLocation) {
        this.getRoadListByBusiLine();
      }
    },
    // 根据选中业务线请求道路列表
    async getRoadListByBusiLine() {
      if (!this.workOrderForm.lat || !this.workOrderForm.lon) {
        return;
      }
      // 中文转英文标识
      const busiLineEn = this.getBusiLineEnByCn(this.workOrderForm.busiLineCn);
      if (!busiLineEn) {
        uni.showToast({ title: '业务线标识异常', icon: 'none' });
        return;
      }

      try {
        uni.showLoading({ title: '获取道路名称中...' });
        const roadRes = await getRoadListByLatLng({
          busiLine: busiLineEn, // 传递业务线英文标识
          latitude: this.workOrderForm.lat,
          longitude: this.workOrderForm.lon
        });
        uni.hideLoading();
        if (Array.isArray(roadRes)) {
          this.roadNameList = roadRes.map((item) => ({
            name: item.roadName || '',
            code: item.roadCode || '',
            id: item.roadId || 0
          }));
        } else {
          this.roadNameList = [{ name: '未查询到道路名称', code: '', id: 0 }];
          uni.showToast({ title: '未查询到该位置的道路信息', icon: 'none' });
        }
      } catch (err) {
        uni.hideLoading();
        console.error('获取道路名称失败：', err);
        uni.showToast({ title: '获取道路名称失败，请重试', icon: 'none' });
        this.roadNameList = [{ name: '获取失败，请重新选择位置', code: '', id: 0 }];
      }
    },
    /**
     * 返回上一页
     */
    navigateBack() {
      uni.navigateBack();
    },
    /**
     * 删除图片
     */
    deleteImg(event, type) {
      console.log('删除图片事件：', event, '类型：', type);
      if (type === 'problemImgsList') {
        this.problemImgsList.splice(event.index, 1);
      } else if (type === 'completeImgsList') {
        this.completeImgsList.splice(event.index, 1);
      }
      // 删除图片后重新校验图片字段
      if (type === 'problemImgsList') {
        this.$refs.workOrderFormRef.validateField('problemImgs');
      } else if (type === 'completeImgsList') {
        this.$refs.workOrderFormRef.validateField('completeImgs');
      }
      uni.showToast({ title: '图片删除成功', icon: 'success' });
    },
    /**
     * 上传图片
     */
    async uploadImgs(event, type) {
      console.log('上传图片事件：', event, '类型：', type);
      const fileList = Array.isArray(event.file) ? event.file : [event.file];
      const targetImgList = type === 'problemImgsList' ? this.problemImgsList : this.completeImgsList;

      const filePaths = fileList.map(item => item.url);
      const tempItems = fileList.map(item => ({
        ...item,
        status: 'uploading',
        message: '上传中'
      }));
      const startIndex = targetImgList.length;
      targetImgList.push(...tempItems);

      try {
        const uploadResultUrls = await uploadImages({
          filePaths: filePaths,
          ignoreError: true
        });
        console.log('上传成功的URL列表：', uploadResultUrls);

        uploadResultUrls.forEach((url, index) => {
          if (targetImgList[startIndex + index]) {
            targetImgList.splice(startIndex + index, 1, {
              ...fileList[index],
              status: 'success',
              message: '',
              url: url
            });
          }
        });

        if (uploadResultUrls.length < fileList.length) {
          const failCount = fileList.length - uploadResultUrls.length;
          for (let i = uploadResultUrls.length; i < fileList.length; i++) {
            if (targetImgList[startIndex + i]) {
              targetImgList.splice(startIndex + i, 1, {
                ...fileList[i],
                status: 'failed',
                message: '上传失败'
              });
            }
          }
          uni.showToast({ title: `成功上传${uploadResultUrls.length}张，失败${failCount}张`, icon: 'none' });
        } else {
          uni.showToast({ title: `成功上传${fileList.length}张图片`, icon: 'success' });
        }

        // 上传完成后重新校验图片字段
        if (type === 'problemImgsList') {
          this.$refs.workOrderFormRef.validateField('problemImgs');
        } else if (type === 'completeImgsList') {
          this.$refs.workOrderFormRef.validateField('completeImgs');
        }
      } catch (err) {
        console.error('图片上传失败：', err);
        for (let i = 0; i < fileList.length; i++) {
          if (targetImgList[startIndex + i]) {
            targetImgList.splice(startIndex + i, 1, {
              ...fileList[i],
              status: 'failed',
              message: '上传失败'
            });
          }
        }
        uni.showToast({ title: '图片上传失败，请重试', icon: 'none' });

        // 上传失败后重新校验图片字段
        if (type === 'problemImgsList') {
          this.$refs.workOrderFormRef.validateField('problemImgs');
        } else if (type === 'completeImgsList') {
          this.$refs.workOrderFormRef.validateField('completeImgs');
        }
      }
    },
    /**
     * 选择工单位置
     */
    chooseWorkLocation() {
      let that = this;
      uni.chooseLocation({
        success: async (res) => {
          that.workOrderForm.roadName = '';
          that.workOrderForm.roadId = 0;
          that.roadNameList = [];

          that.workOrderForm.workLocation = res.name;
          that.workOrderForm.lat = res.latitude;
          that.workOrderForm.lon = res.longitude;

          that.$refs.workOrderFormRef.validateField('workLocation');
          that.$refs.workOrderFormRef.validateField('roadName');

          // 调用封装的方法，自动携带业务线
          await that.getRoadListByBusiLine();
        },
        fail: (err) => {
          console.error('选择位置失败：', err);
          uni.showToast({ title: '选择位置失败：' + err.errMsg, icon: 'none' });
        }
      });
    },
    /**
     * 选择道路名称
     */
    handleRoadNameSelect(e) {
      console.log('选择道路名称：', e);
      this.workOrderForm.roadName = e.name;
      this.workOrderForm.roadId = e.code;
      this.showRoadName = false;
      this.$refs.workOrderFormRef.validateField('roadName');
    },
    /**
     * 选择问题类型
     */
    handleOrderNameSelect(e) {
      console.log(e);
      this.workOrderForm.orderName = e.name;
      this.showOrderName = false;
      this.$refs.workOrderFormRef.validateField('orderName');
    },
    /**
     * 隐藏键盘
     */
    hideKeyboard() {
      uni.hideKeyboard();
    },
    /**
     * 提取图片URL数组
     */
    getImgUrlList(imgList) {
      return imgList.filter(item => item.status === 'success').map(item => item.url);
    },
    /**
     * 提交工单
     */
    async submitWorkOrder() {
      try {
        // 先执行表单校验
        await this.$refs.workOrderFormRef.validate();

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

        const submitData = {
          roadId: this.workOrderForm.roadId,
          roadName: this.workOrderForm.roadName,
          problemsImgs: this.getImgUrlList(this.problemImgsList),
          endImgs: this.getImgUrlList(this.completeImgsList),
          remark: this.workOrderForm.problemDesc.trim(),
          handleResult: this.workOrderForm.handleResult.trim(),
          latLonType: 2,
          lat: this.workOrderForm.lat,
          lon: this.workOrderForm.lon,
          lonLatAddress: this.workOrderForm.workLocation,
          pressingType: 2,
          orderName: this.workOrderForm.orderName,
          sourceId: 1,
          sourceName: this.workOrderForm.busiLineCn, // 业务线中文名称
          thirdWorkNo: '',
          busiLine: busiLineEn // 业务线英文标识（yl/sz/wy）
        };

        // 显示加载中
        uni.showLoading({ title: '提交中...' });

        // 调用提交接口
        const res = await createQuick(submitData);

        uni.hideLoading();
        uni.showToast({
          title: '工单提交成功',
          icon: 'success',
          duration: 1000
        });

        // 延迟跳转
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages-sub/daily/quick-order/index'
          });
        }, 1000);
      } catch (error) {
        // 隐藏加载框
        uni.hideLoading();

        // 区分是表单校验失败还是接口调用失败
        if (!Array.isArray(error)) {
          // 接口调用失败
          console.error('工单提交失败：', error);
          uni.showToast({
            title: '提交失败，请重试',
            icon: 'none',
            duration: 2000
          });
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
// 全局页面样式
.page-container {
  min-height: 100vh;
}

// 工单表单内容容器
.work-order-form-content {
  background: #fff;
  margin-bottom: 100rpx;
}
</style>