<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>
        <!-- 省市 -->
        <el-row>
          <el-form-item label="区域查询"
            prop="region">
            <el-radio-group v-model="queryParams.region"
              @change="regionChange">
              <el-radio-button label="全国"
                value="全国" />
              <el-radio-button label="省"
                value="省" />
              <el-radio-button label="省-市"
                value="省-市" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="省份"
            prop="province"
            v-show="queryParams.region !== '全国'">
            <el-select v-model="queryParams.provinceId"
              placeholder="请选择省"
              @change="getProCity">
              <el-option v-for="item in provinceList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="城市"
            prop="city"
            v-show="queryParams.region === '省-市'">
            <el-select v-model="queryParams.cityId"
              placeholder="请选择市">
              <el-option v-for="item in cityList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="战区"
            prop="zone">
            <el-select v-model="queryParams.zoneId"
              placeholder="请选择战区"
              clearable
              :disabled="cityManagerPrivilege"
              @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="cityManagerPrivilege"
              clearable
              @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"
        :cell-style="{ 'word-wrap': 'break-word', 'white-space': 'normal' }"
        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"
              @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%">
        <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 in obj.list">
              <template #icon>
                <el-image :src="item.photoUrl"
                  :preview-src-list="[...obj.list.map(o => o.photoUrl)]" />
              </template>
            </el-result>
          </div>
        </el-card>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { useDatePickerOptions } from '@/hooks'
import { getWarZoneListAPI, getChargeListAPI, getTaskListAPI, getProCityAPI, deletePromotionSystemAPI, getPromotionSystemAPI, getPromotionActivityAPI } from '@/api'
import { parseTime } from '@/utils'
import store from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus';

const { recentPickerOptions: pickerOptions, last7Date, todayDate } = useDatePickerOptions(0)
const queryParams = reactive({
  taskStatus: '',
  region: '全国',
  provinceId: undefined,
  cityId: undefined,
  zoneId: undefined,
  managerId: undefined,
  storeName: undefined,
  page: 1,
  pageSize: 10,
  date: todayDate
})
const photoDialogVisible = ref(false)
const photoDialogList = ref([])
const photoLookInfoObj = ref({})
const total = ref(0)

// 城市经理状态为 true
const cityManagerPrivilege = computed(() => {
  return store.state?.value?.user?.userInfo?.privilegeId == 1
})

// 任务状态
const taskStatusList = ref([
  {
    label: '未审批',
    value: 'SUBMITTED'
  },
  {
    label: '已审批',
    value: 'APPROVED'
  },
  {
    label: '全部数据',
    value: ''
  }
])

// 区域查询
const provinceList = ref([])
const cityList = ref([])
const getProCity = async () => {
  const { data } = await getProCityAPI(queryParams)
  if (queryParams.provinceId) {
    queryParams.cityId = undefined
    cityList.value = data.map(item => ({
      label: item.name,
      value: item.num
    }))
  } else {
    provinceList.value = data.map(item => ({
      label: item.name,
      value: item.num
    }))
  }
  getTaskList()
}
getProCity()

// 战区列表
const zoneList = ref([])
const getZoneList = async () => {
  const { data } = await getWarZoneListAPI()
  zoneList.value = data.map(item => {
    return {
      label: item.orgName,
      value: item.qcId
    }
  })
}
getZoneList()

// 负责人列表
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
    }
  })
}
getManagerList()

// 任务列表
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: '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 deleteView = async (row) => {
  await ElMessageBox.confirm('确认删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deletePromotionSystemAPI(row.id)
  // 提示删除成功
  getTaskList()
  ElMessage.success('删除成功')
}

// 获取任务列表
const getTaskList = async () => {

  // 后台省市不要 id，自己查个名字给后台
  queryParams.province = provinceList.value.find(item => item.value === queryParams.provinceId)?.label
  queryParams.city = cityList.value.find(item => item.value === queryParams.cityId)?.label
  // 城市经理查自己，职能角色查所有（需要的是促销系统 id）
  if (cityManagerPrivilege.value) {
    // 城市经理 
    await getManagerList()
    queryParams.managerId = managerList.value.find(item => item.employeeNo === store.state.value.user.userInfo.userName)?.value
    // 先从归属人查询当前登录用户的战区 ID
    queryParams.zoneId = managerList.value.find(item => item.employeeNo === store.state.value.user.userInfo.userName)?.deptQcId
  }

  const { data: { records, totalRecord } } = await getTaskListAPI(queryParams)
  tableList.value = records
  total.value = totalRecord
}
getTaskList()
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) {
    const obj = {
      SUBMITTED: '未审批',
      APPROVED: '已审批'
    }
    return obj[value]
  }
  return value
}

// 区域查询切换
const regionChange = (val) => {
  if (val === '全国') {
    queryParams.provinceId = undefined
    queryParams.cityId = undefined
  } else if (val === '省') {
    queryParams.cityId = undefined
  } else if (val === '省-市') {
    cityList.value = []
    getProCity()
  }
  getTaskList()
}

// 查看照片
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
  }]
}

const currentChange = (page) => {
  queryParams.page = page
  getTaskList()
}
</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>