<template>
  <view class="page">
    <view class="back_bar">
      <BackBar title="选择任务" />
    </view>
    <template v-if="!showSystemTaskForm">
      <!-- 系统任务 -->
      <view class="content">
        <view class="title">
          <text>系统任务</text>
          <image
            :src="`${OSS_URL}/iconfont/down_arrow.png`"
            :class="{ title_arrow: true, rotato: expand.systemTask }"
            mode="scaleToFill"
            @click="handleExpand('systemTask')"
          />
        </view>
        <template v-if="expand.systemTask">
          <view v-for="(i, idx) in systemTaskList" :key="idx" class="task_item">
            <view class="left">
              <image
                :src="`${OSS_URL}/iconfont/system_task_icon.png`"
                mode=""
                class="icon"
                lazy-load
              >
              </image>
              <text class="name">{{ i.name }}</text>
            </view>
            <view class="right">
              <view @click="handleChooseTask(i, 'systemTask')">
                <image
                  class="checked"
                  :src="
                    i.checked
                      ? `${OSS_URL}/iconfont/checked.png`
                      : `${OSS_URL}/iconfont/unchecked.png`
                  "
                  mode=""
                  lazy-load
                >
                </image>
              </view>
            </view>
          </view>
        </template>
      </view>
      <!-- 自定义任务 -->
      <view class="content custom">
        <view class="title">
          <text>自定义任务</text>
          <image
            :src="`${OSS_URL}/iconfont/down_arrow.png`"
            :class="{ title_arrow: true, rotato: expand.customTask }"
            mode="scaleToFill"
            @click="handleExpand('customTask')"
          />
        </view>
        <template v-if="expand.customTask">
          <view v-for="(i, idx) in customTaskList" :key="idx" class="task_item">
            <view class="left">
              <image
                :src="`${OSS_URL}/iconfont/custom_task_icon.png`"
                mode=""
                class="icon"
                lazy-load
              >
              </image>
              <text class="name">{{ i.name }}</text>
            </view>
            <view class="right">
              <view class="delete" @click="handleDeleteTask(i.id)">删除</view>
              <view @click="handleChooseTask(i, 'customTask')">
                <image
                  class="checked"
                  :src="
                    i.checked
                      ? `${OSS_URL}/iconfont/checked.png`
                      : `${OSS_URL}/iconfont/unchecked.png`
                  "
                  mode=""
                  lazy-load
                >
                </image>
              </view>
            </view>
          </view>
          <view class="defined" @click="handleUserDefined"> + 自定义任务内容 </view>
        </template>
      </view>
    </template>
    <!-- 系统任务数量 -->
    <view v-else class="system">
      <view class="system_title">{{ chooseTask?.name }}</view>
      <view class="system_task">
        <view class="system_task_label"
          ><text style="color: red">*</text>{{ chooseTask?.unit }}</view
        >
        <view class="system_task_input">
          <input
            v-model="formData.targetNum"
            type="number"
            placeholder="请输入"
            class="input_box"
          />
          <view class="handle_icon">
            <view class="up_dowm" @click="handleUpNumber('up')">
              <image :src="`${OSS_URL}/iconfont/number_icon.png`" mode="" class="icon"></image>
            </view>
            <view class="up_dowm" @click="handleUpNumber('down')">
              <image
                :src="`${OSS_URL}/iconfont/number_icon.png`"
                mode=""
                class="icon reduce"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class="footer">
      <button class="btn-primary" @click="submit">{{ btnText }}</button>
    </view>
    <!-- 新增自定义任务 -->
    <CustomPopup
      v-model="showCustomPopup.definedTaskPopup"
      titleText="自定义任务"
      @handleConfirmBtn="handleConfirmPopup(1)"
    >
      <view class="defined_Popup">
        <view class="label">任务名称</view>
        <input
          v-model="customTask.name"
          type="text"
          maxlength="18"
          placeholder="请输入"
          class="input_box"
          placeholder-style="color:#A9AAB5;font-size:30rpx;"
        />
      </view>
    </CustomPopup>
    <!-- 删除提示 -->
    <CustomPopup
      v-model="showCustomPopup.deleteTipPopup"
      titleText="删除提示"
      @handleConfirmBtn="handleConfirmPopup(2)"
    >
      <view class="delete_popup">是否确认删除该任务？</view>
    </CustomPopup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import { taskConfigListApi, addTaskConfigApi, deleteTaskConfigApi } from '@/api';
import CustomPopup from '@/components/CustomPopup/index.vue';
import type { TaskConfigItemType } from '../interface';
const OSS_URL = import.meta.env.VITE_OSS_HOST;
const showCustomPopup = ref({
  definedTaskPopup: false,
  deleteTipPopup: false,
});
const expand = ref({
  systemTask: true,
  customTask: true,
});
const btnText = ref('下一步');

const systemTaskList = ref<TaskConfigItemType[]>(); // 系统任务
const customTaskList = ref<TaskConfigItemType[]>(); // 自定义任务

const customTask = ref({
  name: '',
  deleteId: '',
});
const showSystemTaskForm = ref(false); // 系统任务数量表单
const formData = ref({
  name: '',
  taskConfigId: undefined,
  targetNum: 1,
});
// 展开
function handleExpand(key: string) {
  expand.value[key] = !expand.value[key];
}
const chooseTask = ref<TaskConfigItemType>();
// 获取任务
async function fetchTaskList() {
  try {
    uni.showLoading({
      title: '加载中...',
    });
    let { data } = await taskConfigListApi();
    systemTaskList.value = data.filter(item => item.taskType === 0);
    customTaskList.value = data.filter(item => item.taskType === 1);
    uni.hideLoading();
  } catch (err) {
    uni.hideLoading();
  }
}
// 选择任务
function handleChooseTask(i: TaskConfigItemType, type: string) {
  i.checked = !i.checked;
  chooseTask.value = i.checked ? i : {};
  btnText.value = i.checked && i.taskType ? '确定' : '下一步';
  systemTaskList.value = systemTaskList.value.map(item => {
    if (item.id === i.id && i.checked) {
      return {
        ...item,
        checked: true,
      };
    } else {
      return {
        ...item,
        checked: false,
      };
    }
  });
  customTaskList.value = customTaskList.value.map(item => {
    if (item.id === i.id && i.checked) {
      return {
        ...item,
        checked: true,
      };
    } else {
      return {
        ...item,
        checked: false,
      };
    }
  });
}
// 数量
function handleUpNumber(type) {
  switch (type) {
    case 'up':
      formData.value.targetNum++;
      break;
    case 'down':
      if (formData.value.targetNum === 1) return;
      formData.value.targetNum--;
      break;
  }
}
// 新增自定义任务
function handleUserDefined() {
  customTask.value.name = '';
  showCustomPopup.value.definedTaskPopup = true;
}
// 删除自定义任务
function handleDeleteTask(id) {
  customTask.value.deleteId = id;
  showCustomPopup.value.deleteTipPopup = true;
}
// 弹窗确定按钮
async function handleConfirmPopup(type) {
  switch (type) {
    case 1:
      // 新增
      if (!customTask.value.name) {
        uni.showToast({
          icon: 'none',
          title: '请输入任务名称',
        });
        return;
      }
      try {
        await addTaskConfigApi({
          name: customTask.value.name,
        });
        await fetchTaskList();
        showCustomPopup.value.definedTaskPopup = false;
      } catch (err) {
        console.log(err);
      }

      break;
    case 2:
      // 删除
      try {
        await deleteTaskConfigApi(customTask.value.deleteId);
        await fetchTaskList();
        showCustomPopup.value.deleteTipPopup = false;
      } catch (err) {
        console.log(err);
      }

      break;
  }
}
// 底部按钮
function submit() {
  if (chooseTask.value) {
    formData.value.name = chooseTask.value.name;
    formData.value.taskConfigId = chooseTask.value.id;
    btnText.value = '确定';
    if (chooseTask.value.taskType === 1) {
      // 自定义
      formData.value.targetNum = undefined;
      uni.$emit('updateTask', {
        taskData: JSON.stringify({
          ...formData.value,
        }),
      });
      uni.navigateBack();
    } else {
      // 系统
      if (showSystemTaskForm.value) {
        uni.$emit('updateTask', {
          taskData: JSON.stringify({
            ...formData.value,
            unit: chooseTask.value.unit,
          }),
        });
        uni.navigateBack();
      } else {
        showSystemTaskForm.value = true;
      }
    }
  } else {
    uni.showToast({
      icon: 'none',
      title: '请选择任务',
    });
  }
}
onMounted(() => {
  fetchTaskList();
});
</script>

<style lang="scss" scoped>
.page {
  padding: 0 30rpx 202rpx 30rpx;
  .back_bar {
    margin-bottom: 30rpx;
  }
  .content {
    padding: 0 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-sizing: border-box;
    color: #333;
    font-size: 30rpx;
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx 0;
      color: #0a1f13;
      font-weight: 500;
      line-height: 45rpx;

      .title_arrow {
        width: 30rpx;
        height: 30rpx;
      }
      .rotato {
        transform: rotate(180deg);
      }
    }
    .task_item {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #eee;
      &:last-child {
        border-bottom: none;
      }

      .left {
        display: flex;

        .icon {
          margin-right: 10rpx;
          width: 40rpx;
          height: 40rpx;
        }

        .name {
          max-width: 454rpx;
          line-height: 42rpx;
        }
      }

      .right {
        display: flex;
        align-items: center;

        .delete {
          margin: 0 19rpx 0 0;
          white-space: nowrap;
          color: #ff2828;
        }

        .checked {
          width: 30rpx;
          height: 30rpx;
        }
      }
    }
    .defined {
      padding: 30rpx 0;
      color: #615dff;
    }
  }
  .custom {
    margin-top: 30rpx;
  }
  .defined_Popup {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 160rpx;
    font-size: 30rpx;
    color: #333;

    .label {
      margin-right: 30rpx;
    }

    .input_box {
      padding: 0 20rpx;
      height: 90rpx;
      width: 384rpx;
      background-color: #f9f9fb;
      border-radius: 16rpx;
      text-align: left;
      box-sizing: border-box;
      line-height: 45rpx;
    }
  }
  .delete_popup {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 145rpx;
  }
  .system {
    padding: 30rpx 30rpx 40rpx 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    color: #333;
    box-sizing: border-box;

    &_title {
      margin-bottom: 30rpx;
      font-size: 32rpx;
      font-weight: 500;
    }

    .system_task {
      display: flex;
      align-items: center;
      width: 100%;

      &_label {
        margin-right: 30rpx;
        max-width: 106rpx;
        line-height: 42rpx;
        white-space: nowrap;
      }

      &_input {
        position: relative;
        flex: 1;
        height: 90rpx;
        background-color: #f9f9fb;
        border-radius: 16rpx;
        text-align: left;

        .input_box {
          padding: 24rpx 20rpx;
          box-sizing: border-box;
          height: 100%;
          line-height: 45rpx;
        }

        .handle_icon {
          position: absolute;
          right: 0;
          top: 0;
          width: 70rpx;
          border-left: 1rpx solid #eee;
          z-index: 99;

          .up_dowm {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            height: 45rpx;

            &:first-child {
              border-bottom: 1rpx solid #eee;
            }
            .reduce {
              transform: rotate(180deg);
            }

            .icon {
              width: 30rpx;
              height: 30rpx;
            }
          }
        }
      }
    }
  }
  .footer {
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: center;
    width: 100%;
    height: 172rpx;
    left: 0;
    box-sizing: border-box;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    font-weight: 500;

    button::after {
      border: none;
    }

    .btn-primary {
      margin-top: 16rpx;
      box-sizing: border-box;
      width: 440rpx;
      height: 90rpx;
      background-color: #615dff;
      color: #ffffff;
      border-radius: 20rpx;
      font-size: 30rpx;
      line-height: 90rpx;
    }
  }
}
</style>
