<script lang="ts" setup>
import Selector from '/src/views/reportManage/dataCenter/normalDisplay/components/Selector/index.vue';
import { onMounted, reactive, ref } from 'vue';
import { VxeGridInstance, VxeGridListeners, VxeGridProps, VXETable } from 'vxe-table';
import {
  exportTaskData,
  getCurrencyCodeSelect,
  getOperationSelect,
  getTasks,
  postCreateTask,
  postDeleteTask, postSendMessage,
  postUpdateTask,
  postUpdateTaskStatus
} from '/src/views/reportManage/TaskManage/api.ts';
import { ComponentSize, ElMessage, FormInstance, FormRules } from 'element-plus';
import { Delete, Plus } from '@element-plus/icons-vue';
import { message } from '/@/utils/message';
import { labelInner } from 'echarts/types/src/label/labelStyle';
import { dateType } from '/@/views/reportManage/TaskManage/utils/enum';

const selectorRef = ref(null);
const message = ref('');

//表单
interface taskRuleForm {
  number: string;
  name: string;
  country: string;
  brand: string;
  operation: string[];
  currency: string;
  currencyCodePlatform: string;
  line: string;
  ipaddress: string;
  company: string;
  platform: string;
}

const formSize = ref<ComponentSize>('default');
const dialogFormVisible = ref(false);
const taskRuleFormRef = ref<FormInstance>();
const taskRuleForm = reactive({
  number: '',
  name: '',
  country: '',
  brand: '',
  operation: [],
  currency: '',
  currencyCodePlatform: '',
});
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' }],
  currencyCodePlatform: [{ required: true, message: '请输入平台货币', trigger: 'blur' }],
  line: [{ required: true, message: '请输入线路', trigger: 'blur' }],
  ipaddress: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
  company: [{ required: true, message: '请输入注册公司', trigger: 'blur' }],
  platform: [{ required: true, message: '请输入平台', trigger: 'blur' }],
});
const currencyList = ref([]);

//表格
interface RowVO {
  platformNumber: string;
  platformName: string;
  country: string;
  brandName: string;
  user_name: string;
  currencyCode: string;
  currencyCodePlatform: string;
  child_user_number: number;
  user: [];
  line: string;
  ipaddress: string;
  company: string;
  platform: string;
}

const xGrid = ref<VxeGridInstance<RowVO>>();
const originalDataMap = new Map();
let allTasks = []; // 用于存储所有任务数据

const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: 'inner',
  keepSource: true,
  //showOverflow: true,
  height: 900,
  loading: false,
  round: true,
  toolbarConfig: {
    zoom: {
      iconIn: 'vxe-icon-fullscreen',
      iconOut: 'vxe-icon-minimize'
    },
    slots: {
      buttons: 'toolbar_buttons',
      tools: 'toolbar_tools'
    }
  },
  rowConfig: {
    isHover: true,
  },
  columnConfig: {
    resizable: true,
  },
  pagerConfig: {
    enabled: true,
    total: 20,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30],
  },
  editConfig: {
    trigger: 'manual',
    mode: 'row',
    showStatus: true,
    autoClear: false,
  },
  checkboxConfig: {
    reserve: true,
    highlight: true,
    range: true,
  },
  columns: [
    { type: 'checkbox', width: 50 },
    {
      field: 'platformNumber',
      title: '平台编号',
      editRender: { autofocus: '.vxe-input--inner' },
      slots: { edit: 'number_edit' },
      minWidth: 97
    },
    {
      field: 'platformName',
      title: '平台名称',
      editRender: { autofocus: '.vxe-input--inner' },
      slots: { edit: 'name_edit' },
      align: 'center',
      minWidth: 150
    },
    {
      field: 'country',
      title: '国家',
      editRender: { autofocus: '.vxe-input--inner' },
      slots: { edit: 'country_edit' },
      minWidth: 89,
      align: 'center'
    },
    {
      field: 'brandName',
      title: '品牌',
      editRender: {},
      slots: { edit: 'brand_edit' },
      align: 'center',
      minWidth: 89,
    },
    {
      field: 'user_name',
      title: '填写人',
      editRender: {},
      slots: { edit: 'operation_edit' },
      align: 'center',
      minWidth: 104
    },
    {
      field: 'operater',
      title: '运营',
      editRender: {},
      slots: { edit: 'operater_name_edit' },
      align: 'center',
      minWidth: 104
    },
    {
      field: 'currencyCode',
      title: '平台币种',
      editRender: {},
      slots: { edit: 'currency_edit' },
      align: 'center',
      minWidth: 89
    },
    {
      field: 'currencyCodePlatform',
      title: '回款/余额币种',
      editRender: {},
      slots: { edit: 'currencyCodePlatform_edit' },
      minWidth: 130,
      align: 'center'
    },
    { field: 'line', title: '线路', editRender: {}, slots: { edit: 'line_edit' }, align: 'center', minWidth: 89 },
    { field: 'ipaddress', title: 'IP地址', editRender: {}, slots: { edit: 'ipaddress_edit' }, minWidth: 138 },
    {
      field: 'company',
      title: '注册公司',
      editRender: {},
      slots: { edit: 'company_edit' },
      align: 'center',
      minWidth: 89
    },
    {
      field: 'platform',
      title: '平台',
      editRender: {},
      slots: { edit: 'platform_edit' },
      align: 'center',
      minWidth: 89
    },
    { field: 'status', title: '状态', slots: { default: 'status_default' }, align: 'center', minWidth: 89 },
    { title: '操作', width: 120, slots: { default: 'operate' } },
  ],
  data: [],
});

const operationList = ref([]);

const gridEvents: VxeGridListeners<RowVO> = {
  pageChange({ 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;
  }
}

function filteredDataChange(newList) {
  if (selectorRef.value) {
    // 重置页码到第一页
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = 1;
    }
    getTaskList(newList.value);
  }
}

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) {
    // 在进入编辑状态前保存原始数据
    originalDataMap.set(row.id, { ...row });
    // 初始化 row.user 确保其与 row.user_name 同步
    if (!row.user || row.user.length === 0) {
      row.user = operationList.value
          .filter(op => row.user_name.includes(op.label))
          .map(op => op.value);
    }
    $grid.setEditRow(row);
  }
};

const clearRowEvent = (row: RowVO) => {
  const $grid = xGrid.value;
  if ($grid) {
    const originalData = originalDataMap.get(row.id);
    if (originalData) {
      // 恢复原始数据
      Object.assign(row, originalData);
      originalDataMap.delete(row.id);
    }
    $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 isDeleteDisabled = computed(() => {
  const $grid = xGrid.value;
  return !$grid || $grid.getCheckboxRecords().length === 0;
});

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' });
    }
  }
};

const requiredFields = [
  { field: 'platformNumber', title: '平台编号' },
  { field: 'platformName', title: '平台名称' },
  { field: 'country', title: '国家' },
  { field: 'brandName', title: '品牌' },
  { field: 'user', title: '填写人' },
  { field: 'currencyCode', title: '平台币种' },
  { field: 'currencyCodePlatform', title: '回款/余额币种' },
  { field: 'line', title: '线路' },
  { field: 'ipaddress', title: 'IP地址' },
  { field: 'company', title: '注册公司' },
  { field: 'platform', title: '平台' },
];

const validateRow = (row) => {
  for (const { field, title } of requiredFields) {
    if (!row[field] || (Array.isArray(row[field]) && row[field].length === 0)) {
      ElMessage.error(`${ title }不能为空`);
      return;
    }
  }
  if (!currencyList.value.includes(row.currencyCode)) {
    ElMessage.error('回款币种格式不正确，请重新选择');
    return;
  }
  if (!currencyList.value.includes(row.currencyCodePlatform)) {
    ElMessage.error('回款/余额币种格式不正确，请重新选择');
    return;
  }
  return true;
};

async function updateRow(row) {
  const $grid = xGrid.value;
  if ($grid) {
    const updatedRowData = {
      id: row.id,
      platformNumber: row.platformNumber,
      platformName: row.platformName,
      country: row.country,
      brandName: row.brandName,
      user: row.user,
      currencyCode: row.currencyCode,
      currencyCodePlatform: row.currencyCodePlatform,
      line: row.line,
      ipaddress: row.ipaddress,
      company: row.company,
      platform: row.platform,
    };
    //console.log('updatedRowData', updatedRowData);
    try {
      const response = await postUpdateTask(updatedRowData);
      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);
    }
  }
}

async function handleStatusChange(row) {
  const $grid = xGrid.value;
  if ($grid) {
    const updatedData = {
      id: row.id,
      status: row.status,
    };
    const query = { partial: 1, };
    try {
      const response = await postUpdateTaskStatus(query, updatedData);
      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) {
    if (!validateRow(row)) {
      return;
    }
    await $grid.clearEdit();
    await updateRow(row);
    await getTaskList();
    gridOptions.loading = true;
    setTimeout(() => {
      gridOptions.loading = false;
    }, 300);
  }
};

async function createTask() {
  const body = {
    country: taskRuleForm.country,
    platformNumber: taskRuleForm.number,
    platformName: taskRuleForm.name,
    brandName: taskRuleForm.brand,
    currencyCode: taskRuleForm.currency,
    currencyCodePlatform: taskRuleForm.currencyCodePlatform,
    line: taskRuleForm.line,
    ipaddress: taskRuleForm.ipaddress,
    company: taskRuleForm.company,
    platform: taskRuleForm.platform,
    user: taskRuleForm.operation,
  };
  try {
    const resp = await postCreateTask(body);
    if (resp.code === 2000) {
      dialogFormVisible.value = false;
      gridOptions.data.push(body);
      await getTaskList(); // 重新获取任务列表
      ElMessage({ message: '创建成功', type: 'success', });
    }
  } catch (error) {
    ElMessage({ message: '创建失败', type: 'error', });
  }
}

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const isDuplicate = allTasks.some(task => String(task.platformNumber) === String(taskRuleForm.number));
      if (isDuplicate) {
        await ElMessage({ message: '平台编号已存在，请重新输入', type: 'warning' });
        return;
      }

      if (!currencyList.value.includes(taskRuleForm.currency)) {
        await ElMessage({ message: '回款币种无效，请重新选择', type: 'warning' });
        return;
      }

      if (!currencyList.value.includes(taskRuleForm.currencyCodePlatform)) {
        await ElMessage({ message: '回款/余额币种无效，请重新选择', type: 'warning' });
        return;
      }

      await createTask();
      taskRuleFormRef.value.resetFields();
    }
  });
};

async function handleExport() {
  gridOptions.loading = true;
  const response = await exportTaskData();
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', '店铺数据.xlsx');
  document.body.appendChild(link);
  link.click();
  gridOptions.loading = false;
  ElMessage.success('导出数据成功');
}

function handleClose(done: Function) {
  if (taskRuleFormRef.value) taskRuleFormRef.value.resetFields();
  done();
}

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);
  }
}

async function fetchCurrencyList() {
  try {
    const response = await getCurrencyCodeSelect(); // 替换为你的后端接口
    currencyList.value = response.data;
  } catch (error) {
    ElMessage.error('请求失败');
  }
}

const querySearch = (queryString, cb) => {
  const results = queryString
      ? currencyList.value.filter(currency => currency.toLowerCase().includes(queryString.toLowerCase()))
      : currencyList.value;
  cb(results);
};

const handleSelect = item => {
  taskRuleForm.currency = item;
};

const handleCurrencyCodePlatformSelect = item => {
  taskRuleForm.currencyCodePlatform = item;
};

function handleRowSelect(item, row) {
  row.currencyCode = item;
}

function handelRowCurrencyCodePlatformSelect(item, row) {
  row.currencyCodePlatform = item;
}

const cellStyle = () => {
  return {
    fontSize: '13px',
    fontWeight: '500',
  };
};

const headerCellStyle = () => {
  return {
    fontSize: '14px',
  };
};

//发送通知
async function sendMessage(selectedValue: string) {
  const body = {
    date_type: selectedValue,
  };
  try {
    const response = await postSendMessage(body);
    if (response.code === 2000) {
      ElMessage.success('发送成功');
    } else if (response.code == 400) {
      ElMessage.warning(`${ response.data.description }`);
    } else {
      ElMessage.error('发送失败');
    }
  }catch (error) {
  }
}

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

<template>
  <el-card class="custom-card-style flex gap-1.5 justify-between mx-8">
    <Selector ref="selectorRef" @update:filteredData="filteredDataChange" :showOperationSearch="true" />
  </el-card>
  <el-card class="mx-8 my-3">
    <div style="position: relative">
      <vxe-grid ref="xGrid" :cell-style="cellStyle" :header-cell-style="headerCellStyle" stripe v-bind="gridOptions"
                v-on="gridEvents">
        <template #toolbar_buttons>
          <el-button :icon="Plus" plain type="success" @click="dialogFormVisible = true"> 添加任务</el-button>
          <el-dropdown style="padding: 0 10px;" trigger="click">
            <el-button type="primary" plain>
              <el-icon class="el-icon--left"><arrow-down /></el-icon>发送通知
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="info of dateType" @click="sendMessage(info.value)">{{ info.label }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button :disabled="isDeleteDisabled" :icon="Delete" plain type="danger" @click="removeEvent">删除
          </el-button>
        </template>
        <template #toolbar_tools>
          <div class="mx-3.5">
            <vxe-button circle icon="vxe-icon-download" @click="handleExport"></vxe-button>
          </div>
        </template>
        <template #operate="{ row }">
          <template v-if="hasActiveEditRow(row)">
            <vxe-button content="取消" type="text" @click="clearRowEvent(row)"></vxe-button>
            <vxe-button content="保存" status="success" type="text" @click="saveRowEvent(row)"></vxe-button>
          </template>
          <template v-else>
            <el-button icon="Edit" type="text" @click="editRowEvent(row)"></el-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 #line_edit="{ row }">
          <vxe-input v-model="row.line"></vxe-input>
        </template>
        <template #ipaddress_edit="{ row }">
          <vxe-input v-model="row.ipaddress"></vxe-input>
        </template>
        <template #company_edit="{ row }">
          <vxe-input v-model="row.company"></vxe-input>
        </template>
        <template #platform_edit="{ row }">
          <vxe-input v-model="row.platform"></vxe-input>
        </template>
        <template #status_default="{ row }">
          <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              @change="handleStatusChange(row)"
          />
        </template>
        <template #operation_edit="{ row }">
          <vxe-select v-model="row.user" multiple>
            <vxe-option v-for="item in operationList" :key="item.value" :label="item.label"
                        :value="item.value"></vxe-option>
          </vxe-select>
        </template>
        <template #operater_name_edit="{ row }">
          <vxe-input v-model="row.operater"></vxe-input>
        </template>
        <template #currency_edit="{ row }">
          <!--<vxe-input v-model="row.currencyCode"></vxe-input>-->
          <el-autocomplete
              v-model="row.currencyCode"
              :debounce="100"
              :fetch-suggestions="querySearch"
              :trigger-on-focus="false"
              clearable
              @select="item => handleRowSelect(item, row)"
          >
            <template v-slot="{ item }">
              <div>{{ item }}</div>
            </template>
          </el-autocomplete>
        </template>
        <template #currencyCodePlatform_edit="{ row }">
          <el-autocomplete
              v-model="row.currencyCodePlatform"
              :debounce="100"
              :fetch-suggestions="querySearch"
              :trigger-on-focus="false"
              clearable
              @select="item => handelRowCurrencyCodePlatformSelect(item,row)"
          >
            <template v-slot="{ item }">
              <div>{{ item }}</div>
            </template>
          </el-autocomplete>
        </template>
      </vxe-grid>
    </div>
  </el-card>
  <el-dialog v-model="dialogFormVisible" :before-close="handleClose" style="border-radius: 10px;" title="新建任务"
             width="500">
    <el-form
        ref="taskRuleFormRef"
        :model="taskRuleForm"
        :rules="rules"
        :size="formSize"
        class="demo-taskRuleForm"
        label-width="auto"
        status-icon
        style="max-width: 600px">
      <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" collapse-tags collapse-tags-tooltip multiple
                   placeholder="请选择录入人员">
          <el-option v-for="item in operationList" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="平台币种" prop="currency">
        <el-autocomplete
            v-model="taskRuleForm.currency"
            :debounce="100"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            clearable
            placeholder="请输入回款币种"
            @select="handleSelect"
        >
          <template v-slot="{ item }">
            <div>{{ item }}</div> <!-- 确保正确显示每个选项 -->
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="回款/余额币种" prop="currencyCodePlatform">
        <el-autocomplete
            v-model="taskRuleForm.currencyCodePlatform"
            :debounce="100"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            clearable
            placeholder="请输入回款/余额币种"
            @select="handleCurrencyCodePlatformSelect"
        >
          <template v-slot="{ item }">
            <div>{{ item }}</div> <!-- 确保正确显示每个选项 -->
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="线路" prop="line">
        <el-input v-model="taskRuleForm.line" placeholder="请输入线路" />
      </el-form-item>
      <el-form-item label="IP地址" prop="ipaddress">
        <el-input v-model="taskRuleForm.ipaddress" placeholder="请输入IP地址" />
      </el-form-item>
      <el-form-item label="注册公司" prop="company">
        <el-input v-model="taskRuleForm.company" placeholder="请输入注册公司" />
      </el-form-item>
      <el-form-item label="平台" prop="platform">
        <el-input v-model="taskRuleForm.platform" 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;
  margin-top: 15px;
  margin-bottom: 5px;
}

.el-card {
  border: none;
  box-shadow: none;
}

.el-card:hover {
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
  0 4px 6px -2px rgba(0, 0, 0, 0.05);
  border-color: #eee;
  transition: all 0.2s ease-in-out;
}

</style>
