<template>
  <div class="trade-group table_form-container">
    <el-form-item label="交易组时间设置">
      <el-button type="primary" @click="addTableItem" v-auth="'contractVariety_createGroup'">添加</el-button>
    </el-form-item>
    <!-- 表格 -->
    <div class="table-box">
      <table v-loading="loading">
        <template v-for="(item, index) in tradeGroupTree" :key="item.id">
          <tr>
            <td style="width: 50px">顺序</td>
            <td style="width: 120px" rowspan="2">
              <el-input style="width: 100px" v-if="item.editStatus" v-model="item.name" />
              <span v-else>{{ item.name }}</span>
            </td>
            <td style="width: 70px">夏令时</td>
            <td style="width: 60px">
              <el-input v-if="item.editStatus" v-model="item.x_m" />
              <span v-else>{{ item.x_m }}</span>
            </td>
            <td style="width: 50px">月</td>
            <td style="width: 60px">
              <el-input v-if="item.editStatus" v-model="item.x_w" />
              <span v-else>{{ item.x_w }}</span>
            </td>
            <td style="width: 50px">周</td>
            <td style="width: 60px">
              <el-input v-if="item.editStatus" v-model="item.x_d" />
              <span v-else>{{ item.x_d }}</span>
            </td>
            <td style="width: 50px">日</td>
            <td style="width: 90px">交易时间</td>
            <td class="time-picker-box">
              <template v-if="item.editStatus">
                <template v-if="item?.x_time_list">
                  <el-time-picker v-for="(time, timeIndex) in item?.x_time_list" :key="timeIndex"
                    v-model="item.x_time_list[timeIndex]" style="width: 180px; flex: 0 0 auto" format="HH:mm:ss"
                    value-format="HH:mm:ss" :picker-options="{
                      selectableRange: '09:00:00 - 18:00:00',
                    }" is-range />
                </template>
                <img src="@/assets/images/trade/group/add.png" @click="addTime(index, 'x_time_list')" />
              </template>
              <template v-else>
                <template v-if="item?.x_time_list">
                  <span v-for="(time, timeIndex) in item?.x_time_list" :key="timeIndex">
                    {{ time[0] }} - {{ time[1] }}
                  </span>
                </template>
              </template>
            </td>
            <td rowspan="2" style="width: 140px">
              <el-button type="primary" v-if="!item.editStatus" @click="item.editStatus = true"
                v-auth="'contractVariety_editGroup'">编辑</el-button>
              <el-button type="danger" v-if="!item.editStatus" @click="deleteGroup(item.id, index)"
                v-auth="'contractVariety_delGroup'">删除</el-button>
              <el-button type="primary" v-if="item.editStatus" @click="submitItem(index)"
                v-auth="'contractVariety_editGroup'">确认</el-button>
              <el-button type="danger" v-if="item.editStatus" @click="item.editStatus = false"
                v-auth="'contractVariety_editGroup'">取消</el-button>
            </td>
          </tr>
          <tr>
            <td>{{ index + 1 }}</td>
            <td>冬令时</td>
            <td>
              <el-input v-if="item.editStatus" v-model="item.d_m" />
              <span v-else>{{ item.d_m }}</span>
            </td>
            <td>月</td>
            <td>
              <el-input v-if="item.editStatus" v-model="item.d_w" />
              <span v-else>{{ item.d_w }}</span>
            </td>
            <td>周</td>
            <td>
              <el-input v-if="item.editStatus" v-model="item.d_d" />
              <span v-else>{{ item.d_d }}</span>
            </td>
            <td>日</td>
            <td>交易时间</td>
            <td class="time-picker-box">
              <template v-if="item.editStatus">
                <template v-if="item?.d_time_list">
                  <el-time-picker v-for="(time, timeIndex) in item?.d_time_list" :key="timeIndex"
                    v-model="item.d_time_list[timeIndex]" style="width: 180px; flex: 0 0 auto" format="HH:mm:ss"
                    value-format="HH:mm:ss" :picker-options="{
                      selectableRange: '09:00:00 - 18:00:00',
                    }" is-range />
                </template>
                <img src="@/assets/images/trade/group/add.png" @click="addTime(index, 'd_time_list')" />
              </template>
              <template v-else>
                <template v-if="item?.d_time_list">
                  <span v-for="(time, timeIndex) in item?.d_time_list" :key="timeIndex">
                    {{ time[0] }} - {{ time[1] }}
                  </span>
                </template>
              </template>
            </td>
          </tr>
        </template>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { usePageLoading } from '@/composables/useLoading'

// 按钮 loading
const { loading, startLoading, stopLoading } = usePageLoading()
defineOptions({
  name: 'Times'
})
// 接口
import {
  getGroupListApi,
  addGroupApi,
  editGroupApi,
  deleteGroupApi,
} from '@/api/modules/trade/group'
import { ElMessageBox } from 'element-plus'

/**
 * @description: 定义表格数据
 */
const tradeGroupTree = ref<any[]>([])

const addTableItem = () => {
  tradeGroupTree.value.unshift({
    name: '',
    x_m: '',
    x_w: '',
    x_d: '',
    x_time_list: [[]],
    d_m: '',
    d_w: '',
    d_d: '',
    d_time_list: [[]],
    editStatus: true,
  })
}

const addTime = (idx: number, key: string) => {
  if (tradeGroupTree.value[idx][key].length >= 4) return ElMessage.warning('最多添加4个时间段')
  tradeGroupTree.value[idx][key].push([])
}

const submitItem = (idx: number) => {
  const submitObj = {
    name: tradeGroupTree.value[idx].name,
    x_m: tradeGroupTree.value[idx].x_m,
    x_w: tradeGroupTree.value[idx].x_w,
    x_d: tradeGroupTree.value[idx].x_d,
    d_m: tradeGroupTree.value[idx].d_m,
    d_w: tradeGroupTree.value[idx].d_w,
    d_d: tradeGroupTree.value[idx].d_d,
    x_start_time1: tradeGroupTree.value[idx].x_time_list[0]?.[0] || null,
    x_end_time1: tradeGroupTree.value[idx].x_time_list[0]?.[1] || null,
    x_start_time2: tradeGroupTree.value[idx].x_time_list[1]?.[0] || null,
    x_end_time2: tradeGroupTree.value[idx].x_time_list[1]?.[1] || null,
    x_start_time3: tradeGroupTree.value[idx].x_time_list[2]?.[0] || null,
    x_end_time3: tradeGroupTree.value[idx].x_time_list[2]?.[1] || null,
    x_start_time4: tradeGroupTree.value[idx].x_time_list[3]?.[0] || null,
    x_end_time4: tradeGroupTree.value[idx].x_time_list[3]?.[1] || null,
    d_start_time1: tradeGroupTree.value[idx].d_time_list[0]?.[0] || null,
    d_end_time1: tradeGroupTree.value[idx].d_time_list[0]?.[1] || null,
    d_start_time2: tradeGroupTree.value[idx].d_time_list[1]?.[0] || null,
    d_end_time2: tradeGroupTree.value[idx].d_time_list[1]?.[1] || null,
    d_start_time3: tradeGroupTree.value[idx].d_time_list[2]?.[0] || null,
    d_end_time3: tradeGroupTree.value[idx].d_time_list[2]?.[1] || null,
    d_start_time4: tradeGroupTree.value[idx].d_time_list[3]?.[0] || null,
    d_end_time4: tradeGroupTree.value[idx].d_time_list[3]?.[1] || null,
  }
  if (tradeGroupTree.value[idx].id) {
    editGroupApi({
      ...submitObj,
      id: tradeGroupTree.value[idx].id,
      sort: tradeGroupTree.value[idx].sort,
    }).then((res) => {
      getGroupList()
    })
  } else {
    addGroupApi({ ...submitObj }).then((res) => {
      getGroupList()
    })
  }
}

const deleteGroup = (id: number, idx: number) => {
  if (!id) {
    tradeGroupTree.value.splice(idx, 1)
    return
  }
  ElMessageBox.confirm('确认删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    deleteGroupApi({ id }).then(() => {
      getGroupList()
    })
  })
}

/**
 * @description: 定义公共请求数据方法
 */
const getGroupList = async () => {
  startLoading()
  try {
    const data = await getGroupListApi()
    data.forEach((item: any) => {
      item.editStatus = false
      item.x_time_list = []
      if (item.x_start_time1 && item.x_end_time1) {
        item.x_time_list.push([item.x_start_time1, item.x_end_time1])
      }
      if (item.x_start_time2 && item.x_end_time2) {
        item.x_time_list.push([item.x_start_time2, item.x_end_time2])
      }
      if (item.x_start_time3 && item.x_end_time3) {
        item.x_time_list.push([item.x_start_time3, item.x_end_time3])
      }
      if (item.x_start_time4 && item.x_end_time4) {
        item.x_time_list.push([item.x_start_time4, item.x_end_time4])
      }

      item.d_time_list = []
      if (item.d_start_time1 && item.d_end_time1) {
        item.d_time_list.push([item.d_start_time1, item.d_end_time1])
      }
      if (item.d_start_time2 && item.d_end_time2) {
        item.d_time_list.push([item.d_start_time2, item.d_end_time2])
      }
      if (item.d_start_time3 && item.d_end_time3) {
        item.d_time_list.push([item.d_start_time3, item.d_end_time3])
      }
      if (item.d_start_time4 && item.d_end_time4) {
        item.d_time_list.push([item.d_start_time4, item.d_end_time4])
      }
    })
    console.log('data', data)
    tradeGroupTree.value = data
  } catch (e: any) {
    console.log(e)
    ElMessage.error(e.msg)
  } finally {
    stopLoading()
  }
}

/**
 * @description: 页面加载完成需要请求的数据
 */
onMounted(() => {
  getGroupList()
})
</script>

<style scoped lang="scss">
.trade-group {
  overflow-y: scroll;
}

/* 给 table 及所有 td 加边框 */
table {
  border-collapse: collapse;
  width: 100%;
  table-layout: auto;
  /* 宽度自适应内容 */

  .time-picker-box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;

    img {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
  }

  td {
    height: 59px;
    border: 1px solid #dcdfe6;
    padding: 4px 8px;
    /* 内边距缩小 */
    text-align: center;
    font-size: 12px;
    /* 文字变小 */
    white-space: nowrap;
    /* 文字不换行 */
    vertical-align: middle;
    /* 垂直居中 */

    /* 时间选择器容器：两个选择器横排不换行 */
    :deep(.el-time-picker) {
      display: inline-block;

      .el-range-editor {
        width: 100px;
        /* 缩小时间选择器宽度 */
        font-size: 12px;
      }

      .el-range-input {
        font-size: 12px;
      }
    }

    /* input 输入框也缩小 */
    :deep(.el-input) {
      width: 40px;

      .el-input__inner {
        font-size: 12px;
        height: 28px;
      }
    }

    /* 按钮缩小 */
    :deep(.el-button) {
      padding: 5px 10px;
      font-size: 12px;
    }
  }
}
</style>
