<template>
  <div class="mobile-page-container">
    <!-- 常规陈列 -->
    <div class="item"
      v-for="(obj, index) in displayGroup">
      <p class="title">常规陈列{{ index + 1 }}：</p>
      <van-cell-group inset>
        <van-field v-model="obj.modal"
          name="modal"
          label="形式"
          placeholder="请输入形式"
          auto-complete="off"
          :rules="[{ required: true, message: '请输入形式' }]"
          @change="handleModalityChange(index)" />
        <van-field v-model="obj.cost"
          name="cost"
          type="number"
          label="费用"
          placeholder="费用"
          auto-complete="off"
          :rules="[{ required: true, message: '请输入费用' }]"
          @change="handleCostChange(index)" />
        <van-field label="常规陈列照片"
          label-align="top"
          class="header-photo-section">
          <template #input>
            <van-uploader :max-count="2"
              accept="image/*"
              capture="camera"
              :model-value="obj.photoArr"
              :name="index"
              :after-read="displayPhotosRead"
              preview-size="78"
              @delete="deletedisplayPhotos">
            </van-uploader>
          </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="form.cgclRiskRArr"
        direction="horizontal"
        shape="square"
        @change="handleOverallChange">
        <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 } from '@/api'
import useUserStore from '@/store/modules/user'
import { v4 as uuidv4 } from 'uuid'

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 handleModalityChange = async (index) => {
  await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      ...displayGroup.value[index]
    }
  })

  showNotify({ type: 'success', message: '形式，保存成功' })
}
// 费用修改
const handleCostChange = async (index) => {

  await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      ...displayGroup.value[index]
    }
  })

  showNotify({ type: 'success', message: '费用，保存成功' })
}
// 上传照片
const displayPhotosRead = async (file, { name, index }) => {
  // name：是当前照片组件所在陈列组的索引
  // index: 当前照片组的索引
  const target = displayGroup.value[name]

  const pictureUrl = await uploadFileToOSSAPI(`risk/displayPhoto/${useUserStore().empInfo.empNo}/${props.form.storeCode}/${uuidv4()}.png`, file.file)
  target.photoArr.push({
    url: pictureUrl
  })

  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) => {
  const target = displayGroup.value[index]
  await createInspectionTaskDetailAPI({
    taskDetail: {
      rstId: props.form.rstId,
      rstdId: target.rstdId,
      riskRArr: target.riskRArr
    }
  })
  showNotify({ type: 'success', message: '核查结果，保存成功' })
}

/*************** 总体核查结果 ***************/
const handleOverallChange = async () => {
  if (props.isInitializing) return
  await createInspectionTaskAPI({
    rstId: props.form.rstId,
    cgclRiskRArr: props.form.cgclRiskRArr
  })
  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);
    }

    /* 每个分组 */
    .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>