<script setup lang="ts">
import Selector from '/src/views/reportManage/dataCenter/normalDisplay/components/Selector/index.vue';
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import { VXETable, VxeGridInstance, VxeGridProps, VxeGridListeners } from 'vxe-table';
import {
  getTasks,
  postCreateTask,
  getOperationSelect,
  postUpdateTask,
  postDeleteTask
} from '/src/views/reportManage/TaskManage/api.ts';
import { ComponentSize, ElMessage, FormInstance, FormRules } from 'element-plus';


//表单
interface taskRuleForm {
  number: string;
  name: string;
  country: string;
  brand: string;
  operation: string[];
  currency: string;
}

const formSize = ref<ComponentSize>('default');
const dialogFormVisible = ref(false);
const taskRuleFormRef = ref<FormInstance>();
const taskRuleForm = reactive({
  number: '',
  name: '',
  country: '',
  brand: '',
  operation: '',
  currency: '',
});
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const rules = reactive<FormRules>({
  number: [{required: true, message: '请输入平台编号', trigger: 'blur'},],
  name: [{required: true, message: '请输入平台名称', trigger: 'blur'}],
  country: [{required: true, message: '请输入国家', trigger: 'blur'}],
  brand: [{required: true, message: '请输入品牌', trigger: 'blur'}],
  operation: [{required: true, message: '请选择运营', trigger: 'change'}],
  currency: [{required: true, message: '请输入货币', trigger: 'blur'}],
});

//表格
let page = 1;
let limit = 10;


interface RowVO {
  platformNumber: string;
  platformName: string;
  country: string;
  brandName: string;
  user_name: string;
  currencyCode: string;
  child_user_number: number;
  user: [];
}

const xGrid = ref<VxeGridInstance<RowVO>>();

const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: false,
  keepSource: true,
  showOverflow: true,
  height: 1000,
  loading: false,
  round: true,
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  rowConfig: {
    isHover: true,
  },
  columnConfig: {
    resizable: true,
  },
  pagerConfig: {
    enabled: true,
    total: 20,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30],
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true,
  },
  checkboxConfig: {
    reserve: true,
    highlight: true,
    range: true,
  },
  columns: [
    {type: 'checkbox', width: 50},
    // {type: 'seq', title: 'ID', width: 120},
    {
      field: 'platformNumber',
      title: '平台编号',
      editRender: {autofocus: '.vxe-input--inner'},
      slots: {edit: 'number_edit'},
      sortable: true,
    },
    {
      field: 'platformName',
      title: '平台名称',
      editRender: {autofocus: '.vxe-input--inner'},
      slots: {edit: 'name_edit'}
    },
    {field: 'country', title: '国家', editRender: {autofocus: '.vxe-input--inner'}, slots: {edit: 'country_edit'}},
    {field: 'brandName', title: '品牌', editRender: {}, slots: {edit: 'brand_edit'}},
    {field: 'user_name', title: '运营', editRender: {}, slots: {edit: 'operation_edit'}},
    {field: 'currencyCode', title: '汇款币种', editRender: {}, slots: {edit: 'currency_edit'}},
    {field: 'child_user_number', title: '录入人员数', editRender: {}, slots: {edit: 'quantity_edit'}},
    {title: '操作', width: 300, slots: {default: 'operate'}},
  ],
  data: [],
});

const operationList = ref([]);
const quantityList = ref([]);

// 分页
const gridEvents: VxeGridListeners<RowVO> = {
  pageChange({currentPage, pageSize}) {
    // console.log(currentPage, pageSize)
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = currentPage;
      gridOptions.pagerConfig.pageSize = pageSize;
      getTaskList();
    }
  },
};

async function getTaskList(filters = {}) {
  try {
    gridOptions.loading = true;
    const response = await getTasks({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
      ...filters,
  });
    gridOptions.data = response.data;
    gridOptions.pagerConfig.total = response.total;
  }catch (error) {
      console.error('Error fetching task data:', error);
    } finally {
      gridOptions.loading = false;
    }
  }

const selectorRef = ref(null);

function filteredDataChange(newList) {
  // console.log('newList:', newList.value);
  if (selectorRef.value) {
    getTaskList(newList.value);
    // gridOptions.data = newList.value;
  }
}

/**
 * 判断当前编辑行
 * @param {RowVO} row 当前行
 * @return {boolean}
 */
const hasActiveEditRow = (row: RowVO) => {
  const $grid = xGrid.value;
  if ($grid) {
    return $grid.isEditByRow(row);
  }
  return false;
};

const editRowEvent = (row: RowVO) => {
  const $grid = xGrid.value;
  if ($grid) {
    $grid.setEditRow(row);
  }
};

//清除编辑状态
const clearRowEvent = () => {
  const $grid = xGrid.value;
  if ($grid) {
    $grid.clearEdit();
  }
};

async function deleteTask() {
  const $grid = xGrid.value;
  if ($grid) {
    const selectRecords = $grid.getCheckboxRecords();
    const selectedIds = selectRecords.map(record => record.id);
    // console.log(selectedIds);
    const obj = {keys: selectedIds};
    try {
      const resp = await postDeleteTask(obj);
      if (resp.code === 2000) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        });
        await getTaskList();
      }
    } catch (e) {
      ElMessage({
        message: '删除失败',
        type: 'error',
      });
    }
  }
}

// 删除选中行
const removeEvent = async () => {
  const $grid = xGrid.value;
  if ($grid) {
    const selectRecords = $grid.getCheckboxRecords();
    if (selectRecords.length > 0) {
      const type = await VXETable.modal.confirm('您确定要删除选中的数据?');
      if (type === 'confirm') {
        await deleteTask(selectRecords);
        await $grid.removeCheckboxRow();
      }
    } else {
      await VXETable.modal.message({content: '请选择要删除的数据', status: 'error'});
    }
  }
};

async function updateRow(row: RowVO) {
  const $grid = xGrid.value;
  const transUser = ref('');
  operationList.value.find((item) => {
    if (item.label === row.user_name) {
      transUser.value = item.value;
    } else if (row.user_name === item.value) {
      row.user_name = item.label;
      transUser.value = item.value;
    }
  });
  if ($grid) {
    const updatedRowData = {
      id: row.id,
      platformNumber: row.platformNumber,
      platformName: row.platformName,
      country: row.country,
      brandName: row.brandName,
      user: [transUser.value],
      currencyCode: row.currencyCode,
    };
    // console.log(updatedRowData);
    try {
      const response = await postUpdateTask(updatedRowData);
      console.log(response);
      if (response.code === 2000) {
        ElMessage.success('更新成功');
      } else if (response.code == 400) {
        ElMessage.warning(`${response.data.description}`);
      } else {
        ElMessage.error('更新失败');
      }
    } catch (error) {
      console.log('error:', error);
    }
  }
}

// 保存表格行数据
const saveRowEvent = async (row: RowVO) => {
  const $grid = xGrid.value;
  if ($grid) {
    await $grid.clearEdit();
    await updateRow(row);
    gridOptions.loading = true;
    setTimeout(() => {
      gridOptions.loading = false;
    }, 300);
  }
};

// 保存全部数据
const saveEvent = async () => {
  const $grid = xGrid.value;
  if ($grid) {
    const {insertRecords, removeRecords, updateRecords} = $grid.getRecordset();
    await VXETable.modal.message({
      content: `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`,
      status: 'success',
    });
  }
};

async function createTask() {
  const body = {
    country: taskRuleForm.country,
    platformNumber: taskRuleForm.number,
    platformName: taskRuleForm.name,
    brandName: taskRuleForm.brand,
    currencyCode: taskRuleForm.currency,
    user: [taskRuleForm.operation],
  };
  try {
    const resp = await postCreateTask(body);
  } catch (error) {
    console.error('error:', error);
    await VXETable.modal.message({content: '创建失败，请重试', status: 'error'});
  }
}

// 新建任务
const submitEvent = async () => {
  // 创建一个新的行对象，用于保存表单数据
  const newRow: RowVO = {
    platformNumber: taskRuleForm.number,
    platformName: taskRuleForm.name,
    country: taskRuleForm.country,
    brandName: taskRuleForm.brand,
    user_name: taskRuleForm.operation,
    currencyCode: taskRuleForm.currency,
    child_user_number: '',
  };
  // 将新行添加到表格数据中
  gridOptions.data.push(newRow);
  try {
    await createTask();
    dialogFormVisible.value = false;
    //获取更新表格数据
    await getTaskList();
    gridOptions.loading = true;
    setTimeout(() => {
      gridOptions.loading = false;
    }, 300);
  } catch (error) {
    console.error('Failed to save task:', error);
  }
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await submitEvent();
      await nextTick();
      taskRuleFormRef.value.resetFields();
      await VXETable.modal.message({content: '创建成功', status: 'success'});
    } else {
      // console.log('error submit!', fields);
    }
  });
};

async function fetchOperationSelect() {
  try {
    const resp = await getOperationSelect();
    operationList.value = resp.data.map((item: any) => {
      return {value: item.id, label: item.name};
    });
  } catch (e) {
    console.error('Failed to fetch operation select:', e);
  }
}


onMounted(() => {
  getTaskList();
  fetchOperationSelect();
});
</script>

<template>
  <el-card class="custom-card-style flex gap-1.5 justify-between my-1.5 mx-2">
    <Selector ref="selectorRef" @update:filteredData="filteredDataChange" />
  </el-card>
  <el-card class="mx-2">
    <div style="position: relative">
      <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvents">
        <template #toolbar_buttons>
          <vxe-button icon="vxe-icon-add" plain @click="dialogFormVisible = true"> 添加任务</vxe-button>
          <vxe-button icon="vxe-icon-delete" @click="removeEvent">删除</vxe-button>
          <vxe-button icon="vxe-icon-save" @click="saveEvent">保存</vxe-button>
        </template>
        <template #operate="{ row }">
          <template v-if="hasActiveEditRow(row)">
            <vxe-button content="取消" @click="clearRowEvent"></vxe-button>
            <vxe-button status="primary" content="保存" @click="saveRowEvent(row)"></vxe-button>
          </template>
          <template v-else>
            <vxe-button content="编辑" @click="editRowEvent(row)"></vxe-button>
          </template>
        </template>

        <template #number_edit="{ row }">
          <vxe-input v-model="row.platformNumber"></vxe-input>
        </template>
        <template #name_edit="{ row }">
          <vxe-input v-model="row.platformName"></vxe-input>
        </template>
        <template #country_edit="{ row }">
          <vxe-input v-model="row.country"></vxe-input>
        </template>
        <template #brand_edit="{ row }">
          <vxe-input v-model="row.brandName"></vxe-input>
        </template>
        <template #operation_edit="{ row }">
          <vxe-select v-model="row.user_name" transfer>
            <vxe-option v-for="item in operationList" :key="item.value" :value="item.value"
                        :label="item.label"></vxe-option>
          </vxe-select>
        </template>
        <template #currency_edit="{ row }">
          <vxe-input v-model="row.currencyCode"></vxe-input>
        </template>
        <template #quantity_edit="{ row }">
          <vxe-select v-model="row.child_user_number" transfer>
            <vxe-option v-for="item in quantityList" :key="item.value" :value="item.value"
                        :label="item.label"></vxe-option>
          </vxe-select>
        </template>
      </vxe-grid>
    </div>
  </el-card>
  <el-dialog v-model="dialogFormVisible" title="新建任务" width="500">
    <el-form
        ref="taskRuleFormRef"
        style="max-width: 600px"
        :model="taskRuleForm"
        :rules="rules"
        label-width="auto"
        class="demo-taskRuleForm"
        :size="formSize"
        status-icon>
      <el-form-item label="平台编号" prop="number">
        <el-input v-model="taskRuleForm.number" placeholder="请输入平台编号" />
      </el-form-item>
      <el-form-item label="平台名称" prop="name">
        <el-input v-model="taskRuleForm.name" placeholder="请输入平台名称" />
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-input v-model="taskRuleForm.country" placeholder="请输入国家" />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="taskRuleForm.brand" placeholder="请输入品牌" />
      </el-form-item>
      <el-form-item label="运营" prop="operation">
        <el-select v-model="taskRuleForm.operation" placeholder="请选择运营">
          <el-option v-for="item in operationList" :key="item.value" :value="item.value"
                     :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="回款币种" prop="currency">
        <el-input v-model="taskRuleForm.currency" placeholder="请输入回款币种" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false ;resetForm(taskRuleFormRef)">取消</el-button>
        <el-button type="primary" @click="submitForm(taskRuleFormRef)"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.custom-card-style {
  z-index: 999;
  position: sticky;
  top: 0;
}
</style>
