<template>
  <div class="mobile-page-container">
    <!-- 档期补差 -->
    <div class="item"
      v-for="(obj, index) in displayGroup">
      <p class="title">
        <span>档期补差{{ index + 1 }}：</span>
        <van-icon name="delete"
          size="0.45rem"
          @click="deleteItem(obj, index)" />
      </p>
      <van-cell-group inset>
        <van-field v-model="obj.bcNr"
          name="bcNr"
          label="提报内容"
          placeholder="请输入提报内容"
          auto-complete="off"
          :rules="[{ required: true, message: '请输入提报内容' }]"
          @change="handleModalityChange(index)" />
        <van-field v-model="obj.bcQk"
          name="bcQk"
          label="执行情况"
          placeholder="执行情况"
          auto-complete="off"
          :rules="[{ required: true, message: '请输入执行情况' }]"
          @change="handleCostChange(index)" />
        <van-field label="档期补差照片/视频"
          label-align="top"
          class="header-photo-section">
          <template #input>
            <XLMobileUpload :max-count="5"
              :photoList="obj.photoArr"
              :name="index"
              :supportVideo="true"
              @confirm="displayPhotosRead"
              @delete="deletedisplayPhotos" />
          </template>
        </van-field>
        <van-field label="补差核查结果"
          label-align="top">
          <template #input>
            <van-checkbox-group v-model="obj.riskRArr"
              direction="horizontal"
              shape="square"
              @change="handleVerifyChange(index)">
              <van-checkbox name="已执行">已执行</van-checkbox>
              <van-checkbox name="部分执行">部分执行</van-checkbox>
              <van-checkbox name="绑赠差异">绑赠差异</van-checkbox>
              <van-checkbox name="未执行">未执行</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>
      </van-cell-group>
    </div>
    <!-- 新增按钮 -->
    <van-button class="add-item"
      type="primary"
      @click="createTask">新增一组</van-button>
    <!-- 总体判定 -->
    <!-- <div class="overall">
      <p class="title">档期陈列总体判定结果：</p>
      <van-checkbox-group v-model="overAll.verify"
        direction="horizontal"
        shape="square">
        <van-checkbox name="合格">合格</van-checkbox>
        <van-checkbox name="需整改">需整改</van-checkbox>
        <van-checkbox name="不合格">不合格</van-checkbox>
        <van-checkbox name="虚假">虚假</van-checkbox>
      </van-checkbox-group> 
    </div> -->
  </div>
</template>

<script setup>

import { uploadFileToOSSAPI, createInspectionTaskAPI, createInspectionTaskDetailAPI, deleteInspectionTaskAPI } from '@/api'
import useUserStore from '@/store/modules/user'
import { v4 as uuidv4 } from 'uuid'
import { getFileTypeExt } from '@/utils'

const route = useRoute()
const props = defineProps({
  isInitializing: {
    type: Boolean,
    default: false
  },
  form: {
    type: Object,
    default: () => { }
  }
})

const displayGroup = ref([])

/*************** 陈列组信息 ***************/
// 特殊字段处理
const checkProperty = (list) => {
  list.map(item => {
    item.riskRArr = item.riskRArr || []
    item.photoArr = item.photoArr?.map(o => ({
      url: o
    })) || []
  })
}
// 创建任务组
const createTask = async () => {
  const { data } = await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      detailName: '档期补差'
    }
  })
  checkProperty([data])
  displayGroup.value.push(data)

}
const init = () => {
  // 查询外层是否传入初始数据
  if (props.form.detailMap) {
    if (props.form.detailMap['档期补差']) {
      checkProperty(props.form.detailMap['档期补差'])
      displayGroup.value = props.form.detailMap['档期补差'] || []
      return
    }
  }
  // 没传递则自己至少新建 1 个
  if (displayGroup.value.length === 0) {
    createTask()
  }
}

// 删除分组
const isDeleteNow = ref(false)
const deleteItem = async (obj, index) => {
  // 确认询问框
  showConfirmDialog({
    title: '删除提示',
    message: '确定删除吗？',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    isDeleteNow.value = true
    await deleteInspectionTaskAPI({
      rstdId: obj.rstdId
    })
    displayGroup.value.splice(index, 1)
    nextTick(() => {
      isDeleteNow.value = false
    })
    showNotify({ type: 'success', message: '删除分组成功' })
  })
}
/*************** 基本信息 ***************/
// 提报内容
const handleModalityChange = async (index) => {
  await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      ...displayGroup.value[index],
      // 照片单独处理
      photoArr: displayGroup.value[index].photoArr.map(o => o.url)
    }
  })

  showNotify({ type: 'success', message: '提报内容，保存成功' })
}
// 执行情况
const handleCostChange = async (index) => {

  await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      ...displayGroup.value[index],
      // 照片单独处理
      photoArr: displayGroup.value[index].photoArr.map(o => o.url)
    }
  })

  showNotify({ type: 'success', message: '执行情况，保存成功' })
}
// 上传照片
const displayPhotosRead = async (file, { name, index }) => {
  // name：是当前照片组件所在陈列组的索引
  // index: 当前照片组的索引
  const date = new Date()
  const month = date.getMonth() + 1
  const target = displayGroup.value[name]
  const targetIndex = target.photoArr.length
  target.photoArr[targetIndex] = {
    url: file.content,
    status: 'uploading',
    message: '上传中...'
  }
  const pictureUrl = await uploadFileToOSSAPI(`risk/${date.getFullYear()}-${month}/scheduleAdjustmentPhoto/${useUserStore().empInfo.empNo}/${props.form.storeCode}/${uuidv4()}.${getFileTypeExt(file.file.name)}`, file.file)
  target.photoArr[targetIndex] = {
    url: pictureUrl,
    status: 'done'
  }

  await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      rstdId: target.rstdId,
      photoArr: target.photoArr.map(o => o.url)
    }
  })

  showNotify({ type: 'success', message: '档期补差照片/视频，上传成功' })
}
// 删除照片
const deletedisplayPhotos = async (file, { name, index }) => {
  const target = displayGroup.value[name]
  target.photoArr.splice(index, 1)
  await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      rstdId: target.rstdId,
      photoArr: target.photoArr.map(o => o.url)
    }
  })
  showNotify({ type: 'success', message: '档期补差照片/视频，删除成功' })
}
// 核查结果
const handleVerifyChange = async (index) => {
  if (isDeleteNow.value) return
  const target = displayGroup.value[index]
  await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      rstdId: target.rstdId,
      riskRArr: target.riskRArr
    }
  })
  showNotify({ type: 'success', message: '核查结果，保存成功' })
}

defineExpose({
  init
})
</script>

<style scoped
  lang="scss">
  .mobile-page-container {
    padding: 10px 10px 0 10px;
    background-color: white;
    font-size: 14px;

    /* 公共样式 */
    .title {
      margin: 0;
      font-weight: 900;
      color: var(--main-color);

      display: flex;
      justify-content: space-between;
    }

    /* 每个分组 */
    .item {
      margin-bottom: 10px;

      .van-cell-group {
        padding: 0;
        margin: 0;

        .van-cell {
          padding-left: 0px;
        }

        .header-photo-section {
          margin-top: 10px;

          ::v-deep(.van-uploader__upload) {
            width: 80px !important;
            height: 80px !important;
            border: 1px dashed #ccc;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f8f8f8;
          }
        }

        /* 核查结果 */
        .van-checkbox {
          margin-bottom: 10px;
        }
      }

      &:after {
        content: " ";
        display: block;
        width: 100%;
        border-bottom: 1px solid gray;
      }

    }

    /* 新增一组 */
    .add-item {
      width: 100%;
      height: 30px;
      margin-top: 10px;
    }

    /* 总体判定 */
    .overall {
      background-color: white;
      padding-top: 10px;

      .van-checkbox-group {
        margin-top: 10px;

        .van-checkbox {
          margin-bottom: 10px;
        }
      }
    }
  }
</style>