<template>
  <div class="app-container">
    <div class="container">
      <!-- 查询表单 -->
      <el-form :model="queryParams"
        inline
        label-width="68px">
        <el-form-item label="选择日期"
          prop="date">
          <el-date-picker v-model="queryParams.date"
            type="daterange"
            clearable
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="pickerOptions"
            @change="getTaskList" />
        </el-form-item>
        <el-form-item label="任务状态"
          prop="taskStatus">
          <el-radio-group v-model="queryParams.taskStatus"
            @change="getTaskList">
            <el-radio-button v-for="item in taskStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value" />
          </el-radio-group>
        </el-form-item>
        <!-- 省市 -->
        <SelectProvinceCity :queryParams="queryParams"
          @change="getTaskList" />
        <el-row>
          <el-form-item label="战区"
            prop="zone">
            <el-select v-model="queryParams.zoneId"
              placeholder="请选择战区"
              clearable
              filterable
              :disabled="isCityManager"
              @change="getTaskList">
              <el-option v-for="item in zoneList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="负责人"
            prop="manager">
            <el-select v-model="queryParams.managerId"
              placeholder="请选择负责人"
              :disabled="isCityManager"
              clearable
              filterable
              @change="getTaskList">
              <el-option v-for="item in managerList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="店铺名"
            prop="store">
            <el-input v-model="queryParams.storeName"
              clearable
              @input="getTaskList"
              placeholder="请输入门店名称" />
          </el-form-item>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <el-table :data="tableList"
        border
        style="width: 100%"
        show-overflow-tooltip>
        <el-table-column v-for="item in columns"
          :key="item.label"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="formatter"
          :fixed="item.fixed" />
        <el-table-column label="操作"
          width="200"
          fixed="right">
          <template #default="scope">
            <el-button type="primary"
              @click="lookPhoto(scope.row)"
              text>
              查看照片
            </el-button>
            <el-button type="danger"
              v-if="checkTaskExpire(scope.row)"
              @click="deleteView(scope.row)"
              text>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.pageSize"
        @pagination="getTaskList" />
      <!-- 照片查看弹窗 -->
      <el-dialog :title="photoLookInfoObj.storeName"
        v-model="photoDialogVisible"
        width="60%"
        draggable
        overflow>
        <p>活动记录 ID :{{ photoLookInfoObj.id }}</p>
        <p>活动时间 :{{ photoLookInfoObj.createDate }}</p>
        <el-card v-for="obj in photoDialogList"
          shadow="never">
          <template #header>{{ obj.title }}</template>
          <div class="content">
            <el-result :title="item.time"
              :sub-title="item.title"
              v-for="item, index in obj.list">
              <template #icon>
                <el-image :src="item.photoUrl"
                  :initial-index="index"
                  :preview-src-list="[...obj.list.map(o => o.photoUrl)]" />
              </template>
            </el-result>
          </div>
        </el-card>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { useDatePickerOptions, checkTaskExpire } from '@/hooks'
import { getWarZoneListAPI, getChargeListAPI, getTaskListAPI, deletePromotionSystemAPI, getPromotionSystemAPI, getPromotionActivityAPI } from '@/api'
import { parseTime } from '@/utils'
import { PROMOTION_TASK_STATUS_LIST } from '@/dicts'
import userStore from '@/store/modules/user'
import SelectProvinceCity from '../components/SelectProvinceCity'

const { recentPickerOptions: pickerOptions, todayDate } = useDatePickerOptions(0)
const { proxy } = getCurrentInstance()

// 城市经理状态为 true
const isCityManager = userStore().promotionIdentity
const empInfo = userStore().empInfo

/****************** 搜索参数 ******************/
const taskStatusList = ref(PROMOTION_TASK_STATUS_LIST) // 任务状态
// 战区列表
const zoneList = ref([])
const getZoneList = async () => {
  const { data } = await getWarZoneListAPI()
  zoneList.value = data.map(item => {
    return {
      label: item.orgName,
      value: item.qcId
    }
  })
  // 如果是城市经理，默认设置战区为当前登录的城市经理
  isCityManager && (queryParams.zoneId = managerList.value.find(item => item.employeeNo === empInfo.empNo)?.deptQcId)
}

// 负责人列表
const managerList = ref([])
const getManagerList = async () => {
  const { data } = await getChargeListAPI()
  managerList.value = data.map(item => {
    return {
      label: item.name,
      value: item.id,
      employeeNo: item.employeeNo,
      deptQcName: item.deptQcName,
      deptQcId: item.deptQcId
    }
  })
  // 如果是城市经理，默认设置负责人为当前登录的城市经理
  isCityManager && (queryParams.managerId = managerList.value.find(item => item.employeeNo === empInfo.empNo)?.value)

}

/****************** 任务列表 ******************/
const queryParams = reactive({
  taskStatus: '',
  region: '全国',
  provinceId: undefined,
  cityId: undefined,
  zoneId: undefined,
  managerId: undefined,
  storeName: undefined,
  page: 1,
  pageSize: 10,
  date: todayDate
})
const total = ref(0)
const tableList = ref([])
const columns = ref([
  {
    label: 'ID',
    prop: 'id',
    width: 90,
    fixed: true
  },
  {
    label: '姓名',
    prop: 'temporaryName',
    width: 90,
    fixed: true
  },
  {
    label: '上报日期',
    prop: 'createDate',
    width: 120,
    fixed: true
  },
  {
    label: '星期',
    prop: 'week',
    width: 80
  },
  {
    label: '省份',
    prop: 'province',
    width: 100
  },
  {
    label: '城市',
    prop: 'city',
    width: 100
  },
  {
    label: '经销商',
    prop: 'dealerName',
    width: 250
  },
  {
    label: '门店',
    prop: 'storeName',
    width: 250
  },
  {
    label: '活动模式',
    prop: 'activityPattern',
    width: 100
  },
  {
    label: '活动品项',
    prop: 'prdClass',
    width: 100
  },
  {
    label: '任务状态',
    prop: 'approveStatus',
    width: 150
  },
  {
    label: '上班卡',
    prop: 'clockDto.clockInTime', // 拼接地址  clockInAddress, 经纬度 clockInCoordinates
    width: 300
  },
  {
    label: '午休下班卡',
    prop: 'clockDto.noonClockOutTime', // 拼接地址  noonClockOutAddress, 经纬度 noonClockOutCoordinates
    width: 300
  },
  {
    label: '午休上班卡',
    prop: 'clockDto.noonClockInTime', // 拼接地址  noonClockInAddress, 经纬度 noonClockInCoordinates
    width: 300
  },
  {
    label: '下班卡',
    prop: 'clockDto.clockOutTime', // 拼接地址  clockOutAddress, 经纬度 clockOutCoordinates
    width: 300
  },
  {
    label: '战区',
    prop: 'deptQcOrgName',
    width: 150
  },
  {
    label: '城市经理',
    prop: 'manageName',
    width: 120
  }
]) // 任务列表
// 获取任务列表
const getTaskList = async () => {
  const { data: { records, totalRecord } } = await getTaskListAPI({
    ...queryParams,
    province: queryParams.provinceName,
    city: queryParams.cityName
  })
  tableList.value = records
  total.value = totalRecord
}
const formatter = (row, columns, value) => {
  // 判断有值再转换
  if (columns.property === 'clockDto.clockInTime' && value) {
    return parseTime(value, '{h}:{i}') + '\n' + row['clockDto']['clockInAddress']
  } else if (columns.property === 'clockDto.noonClockOutTime' && value) {
    return parseTime(value, '{h}:{i}') + '\n' + row['clockDto']['noonClockOutAddress']
  } else if (columns.property === 'clockDto.noonClockInTime' && value) {
    return parseTime(value, '{h}:{i}') + '\n' + row['clockDto']['noonClockInAddress']
  } else if (columns.property === 'clockDto.clockOutTime' && value) {
    return parseTime(value, '{h}:{i}') + '\n' + row['clockDto']['clockOutAddress']
  } else if (columns.property === 'week') {
    return parseTime(row['createDate'], '周{a}')
  } else if (columns.property === 'approveStatus' && value) {
    return taskStatusList.value.find(item => item.value === value)?.label
  }
  return value
}

// 删除任务
const deleteView = async (row) => {
  await proxy.$modal.confirm('确认删除该记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deletePromotionSystemAPI(row.id)
  getTaskList()
  proxy.$modal.msgSuccess('删除成功')
}

onMounted(async () => {
  await getManagerList()
  await getZoneList()
  getTaskList()
})

/***************** 查看图片弹窗 *****************/
const photoDialogVisible = ref(false)
const photoDialogList = ref([]) // 图片数据集合
const photoLookInfoObj = ref({})

const lookPhoto = async (row) => { // 查看照片
  photoDialogVisible.value = true
  photoLookInfoObj.value = row
  const result = await getPromotionActivityAPI(row.id)
  const { tgcjPhotoInfos: tgcjPhotoInfosList, tghdPhotoInfos: tghdPhotoInfosList, tgscPhotoInfos: tgscPhotoInfosList } = result.data
  if (tgscPhotoInfosList) {
    var tgscPhotoInfos = [...tgscPhotoInfosList?.map(item => ({
      time: parseTime(item.createTime, '{h}:{i}'),
      photoUrl: item.photoUrl
    }))]
  }
  if (tghdPhotoInfosList) {
    var tghdPhotoInfos = [...tghdPhotoInfosList?.map(item => ({
      time: parseTime(item.createTime, '{h}:{i}'),
      photoUrl: item.photoUrl
    }))]
  }
  if (tgcjPhotoInfosList) {
    var tgcjPhotoInfos = [...tgcjPhotoInfosList?.map(item => ({
      time: parseTime(item.createTime, '{h}:{i}'),
      photoUrl: item.photoUrl
    }))]
  }

  const res = await getPromotionSystemAPI(row.clockDto.id)
  // 判断上班卡，午休下班卡，午休上班卡，下班卡是否有值，有则添加到数组中
  // 数组是二维数组，第一到三是推广数据，第四个是打卡数据
  const { clockInTime, noonClockOutTime, noonClockInTime, clockOutTime } = res.data
  const clockList = []
  if (clockInTime) {
    clockList.push({
      time: parseTime(clockInTime, '{h}:{i}'),
      title: '上班卡',
      photoUrl: res.data.clockInPhoto
    })
  }
  if (noonClockOutTime) {
    clockList.push({
      time: parseTime(noonClockOutTime, '{h}:{i}'),
      title: '午休下班卡',
      photoUrl: res.data.noonClockOutPhoto
    })
  }
  if (noonClockInTime) {
    clockList.push({
      time: parseTime(noonClockInTime, '{h}:{i}'),
      title: '午休上班卡',
      photoUrl: res.data.noonClockInPhoto
    })
  }
  if (clockOutTime) {
    clockList.push({
      time: parseTime(clockOutTime, '{h}:{i}'),
      title: '下班卡',
      photoUrl: res.data.clockOutPhoto
    })
  }

  // 组装数据
  photoDialogList.value = [{
    title: '推广试吃照片',
    list: tgscPhotoInfos
  }, {
    title: '推广互动照片',
    list: tghdPhotoInfos
  }, {
    title: '推广成交照片',
    list: tgcjPhotoInfos
  }, {
    title: '考勤打卡照片',
    list: clockList
  }]
}


</script>


<style scoped
  lang="scss">
  ::v-deep(.el-form-item) {
    width: 350px !important;
  }

  .el-card {
    margin-top: 20px;
  }

  /* 单元格支持 \n 换行 */
  .container .el-table ::v-deep(.cell) {
    white-space: pre-line;
    /* 强制显示 2 行，超出的省略号 */
    /* overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical; */

  }

  ::v-deep(.el-overlay) {
    .el-card__body {


      .content {
        /* display: flex; */
        overflow-y: hidden;
        overflow-x: scroll;
        white-space: nowrap;

        /* 阻止内容换行 */
        &::-webkit-scrollbar-track {
          background: transparent;
          /* 滚动条轨道背景透明 */
        }

        .el-result {
          width: 250px;
          height: 350px;
          display: inline-block;

          .el-result__icon {
            width: 100%;
            height: 100%;
          }

          .el-image {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
</style>