<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,
  postNoticePerson,
  postSendMessage,
  postUpdateManyTask,
  postUpdateTask,
  postUpdateTaskStatus
} from '/src/views/reportManage/TaskManage/api.ts';
import { ComponentSize, ElMessage, FormInstance, FormRules } from 'element-plus';
import { Delete, Message, Plus } from '@element-plus/icons-vue';
import { dateType, requiredFields } from '/@/views/reportManage/TaskManage/utils/enum';
import { taskColumns } from '/@/views/reportManage/TaskManage/utils/columns';

const selectorRef = ref(null);
const message = ref('');
const currencyList = ref([]);// 货币列表

//表单
interface taskRuleForm {
  number: string;
  name: string;
  country: string;
  brand: string;
  operation: string[];
  operater: [];
  currency: string;
  currencyCodePlatform: string;
  line: string;
  ipaddress: string;
  company: string;
  platform: string;
  companyEnglishName: string;
  // address: string;
  juridicalPerson: string;
  // juridicalPersonCreditCard: string;
  // juridicalPersonCreditCardAddress: string;
  // receivablesAccount: string;
  // receivablesAccountCompany: string;
  // vatNumber: string;
  // vatCompany: string;
}

const formSize = ref<ComponentSize>('default');
const dialogFormVisible = ref(false);
const taskRuleFormRef = ref<FormInstance>();
const taskRuleForm = reactive({
  number: '',
  name: '',
  country: '',
  brand: '',
  operation: [],
  operater: [],
  currency: '',
  currencyCodePlatform: '',
  line: '',
  ipaddress: '',
  company: '',
  platform: '',
  companyEnglishName: '',
  juridicalPerson: '',
  department: '',
});

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' }],
  operater: [{ 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' }],
  department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
});

// 修改填写人弹窗
const userDialogFormVisible = ref(false);
const updateSelect = ref(1);

//发送通知弹窗
const noticeDialogFormVisible = ref(false);
const noticeMessage = ref(null);

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

const xGrid = ref<VxeGridInstance<RowVO>>();
const originalData = ref([]);
let allTasks = []; // 用于存储所有任务数据
const operationList = ref([]);// 填写人列表
const filter = ref({}); // 筛选条件

const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: 'inner',
  keepSource: true,
  //showOverflow: true,
  height: 780,
  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: 'click',
    mode: 'row',
    showStatus: true,
    showIcon:false,
    //autoClear: false,
  },
  checkboxConfig: {
    reserve: true,
    highlight: true,
    range: true,
  },
  columns: taskColumns,
  data: [],
});

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

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 = userNameToUser(row.user_name); // 转换 user_name 到 user
    }
    $grid.setEditRow(row);
  }
};

const handleEditActived = ({ row, column }) => {
  if (!row.user || row.user.length === 0) {
    row.user = userNameToUser(row.user_name); // 转换 user_name 到 user
  }
};

const handleEditClosed = ({ row, column }) => {
  // const $grid = xGrid.value;
  if (column.property === 'user_name') {
    // 将 user 转换为 user_name 并更新 row
    row.user_name = userToUserName(row.user);
    // 强制刷新视图
    // $grid.refreshRow(row);
  }
};

// 禁用自动退出编辑模式
const disableAutoExitEdit = () => {
  const $grid = xGrid.value;
  if ($grid) {
    gridOptions.editConfig.autoClear = false; // 手动模式，禁止点击其他地方退出编辑模式
  }
};

// 启用自动退出编辑模式
const enableAutoExitEdit = () => {
  const $grid = xGrid.value;
  if ($grid) {
    gridOptions.editConfig.autoClear = true; // 点击触发退出编辑模式
  }
};

// 将 user 数组转换为 user_name 字符串
function userToUserName(user: string[]): string {
  return operationList.value
      .filter(op => user.includes(op.value))
      .map(op => op.label)
      .join(', ');
}

// 将 user_name 字符串转换为 user 数组
function userNameToUser(user_name: string): string[] {
  return operationList.value
      .filter(op => user_name.includes(op.label))
      .map(op => op.value);
}

// 清除编辑状态并保存已编辑的数据
const clearRowEvent = (row) => {
  const $grid = xGrid.value;
  if ($grid) {
    // 手动保存当前行的数据
    const editRecord = $grid.getEditRecord();
    if (editRecord) {
      const { row: editedRow } = editRecord;
      // 更新原始 row 数据，确保编辑的值被保存
      row.user = editedRow.user;
      row.user_name = userToUserName(editedRow.user);
    }
    // 清除编辑状态
    $grid.clearEdit();
  }
};

// 获取任务列表
async function getTaskList() {
  try {
    gridOptions.loading = true;
    const response = await getTasks({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
      ...filter.value,
    });
    gridOptions.data = response.data;
    originalData.value = JSON.parse(JSON.stringify(response.data));
    gridOptions.pagerConfig.total = response.total;
  } catch (error) {
    console.error('Error fetching task data:', error);
  } finally {
    gridOptions.loading = false;
  }
}

// 筛选器变化
function filteredDataChange(newList) {
  filter.value = newList.value;
  if (selectorRef.value) {
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = 1;
    }
    getTaskList(newList.value);
  }
}

// 全部保存按钮
async function saveEvent(row) {
  clearRowEvent(row);
  const $grid = xGrid.value;
  if ($grid) {
    try {
      const { updateRecords } = $grid.getRecordset();
      const originalDataMap = new Map(originalData.value.map(item => [item.id, item]));

      const updatedRecords = updateRecords.map(record => {
        const originalRecord = originalDataMap.get(record.id);
        if (!originalRecord) return null;

        const updatedFields = {};

        // 比较字段并记录变化
        for (const key in record) {
          // 针对 operater 字段的特殊处理
          if (key === 'operater') {
            // 如果 operater 是字符串，将其转换为数组
            let recordOperater = Array.isArray(record.operater)
                ? record.operater
                : record.operater.split('，').map(item => item.trim()); // 中文逗号分割并去除空格

            // 如果 originalRecord.operater 是字符串，也转换为数组
            let originalOperater = Array.isArray(originalRecord.operater)
                ? originalRecord.operater
                : originalRecord.operater.split('，').map(item => item.trim());

            // 比较两个数组，确保它们不相等时才记录变化
            if (JSON.stringify(recordOperater) !== JSON.stringify(originalOperater)) {
              updatedFields[key] = recordOperater; // 存储更新后的 operater 数组
            }
          } else {
            // 对于非 operater 字段，进行普通的比较
            if (record[key] !== originalRecord[key]) {
              updatedFields[key] = record[key];
            }
          }
        }

        // 如果有变化字段，返回该记录，否则跳过
        if (Object.keys(updatedFields).length > 0) {
          return {
            id: record.id,
            ...updatedFields
          };
        }
        return null;
      }).filter(record => record); // 过滤掉值为 null 的记录

      if (updatedRecords.length > 0) {
        // 调用接口提交更新
        await postUpdateManyTask(updatedRecords);
        await getTaskList();
        await VXETable.modal.message({
          content: `更新 ${ updatedRecords.length } 条`,
          status: 'success',
        });
      } else {
        await VXETable.modal.message({
          content: '没有检测到变化',
          status: 'info',
        });
      }

    } catch (e) {
      console.log('error', e);
    }
  }
}

// 批量修改填写人
async function updateUser() {
  const $grid = xGrid.value;
  if ($grid) {
    const selectRecords = $grid.getCheckboxRecords(); // 获取勾选的表格行
    const selectedUsers = taskRuleForm.operation; // 获取选择的填写人
    const operationType = updateSelect.value; // 获取选择的操作类型

    const updateData = selectRecords.map(record => {
      const existingUsers = userNameToUser(record.user_name) || [];
      let updatedUsers;
      if (operationType === 1) { // 添加操作
        updatedUsers = Array.from(new Set([...existingUsers, ...selectedUsers]));
      } else if (operationType === 2) { // 删除操作
        updatedUsers = existingUsers.filter(user => !selectedUsers.includes(user));
      }
      return {
        id: record.id,
        user: updatedUsers, // 更新后的 user 数组
      };
    });
    try {
      // 调用接口批量保存修改的数据
      await postUpdateManyTask(updateData);
      if (operationType === 1) { // 添加操作
        ElMessage.success('添加成功');
      } else if (operationType === 2) { // 删除操作
        ElMessage.success('删除成功');

      }
      userDialogFormVisible.value = false; // 关闭弹窗
      await getTaskList(); // 重新加载表格数据
    } catch (error) {
      console.error('修改失败', error);
      ElMessage.error('修改失败');
    } finally {
      // 清除表单数据
      taskRuleForm.operation = []; // 清除选择的填写人
      updateSelect.value = 1; // 清除操作类型
    }
  }
}

function updateUserCancel() {
  taskRuleForm.operation = [];
  updateSelect.value = 1;
  userDialogFormVisible.value = false;
}

// 指定人通知
async function noticePerson() {
  const $grid = xGrid.value;
  if ($grid) {
    const selectRecords = $grid.getCheckboxRecords();
    const selectedIds = selectRecords.map(record => record.id);
    const obj = {
      task_list: selectedIds,
      message: noticeMessage.value,
    };
    try {
      const response = await postNoticePerson(obj);
      if (response.code === 2000) {
        ElMessage.success('通知成功');
        noticeDialogFormVisible.value = false; // 关闭弹窗
      } else {
        ElMessage.error('通知失败');
      }
    } catch (error) {
      ElMessage.error('通知失败');
    }
  }
}


function noticePersonCancel() {
  noticeMessage.value = null;
  noticeDialogFormVisible.value = false; // 关闭弹窗
}

// 删除任务
async function deleteTask() {
  const $grid = xGrid.value;
  if ($grid) {
    const selectRecords = $grid.getCheckboxRecords();
    const selectedIds = selectRecords.map(record => record.id);
    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 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,
      operater: Array.isArray(row.operater) ? row.operater : row.operater.split('，').map(item => item.trim()),
      currencyCode: row.currencyCode,
      currencyCodePlatform: row.currencyCodePlatform,
      line: row.line,
      ipaddress: row.ipaddress,
      company: row.company,
      platform: row.platform,
      companyEnglishName: row.companyEnglishName,
      // address: row.address,
      juridicalPerson: row.juridicalPerson,
      department: row.department,
      // juridicalPersonCreditCard: row.juridicalPersonCreditCard,
      // juridicalPersonCreditCardAddress: row.juridicalPersonCreditCardAddress,
      // receivablesAccount: row.receivablesAccount,
      // receivablesAccountCompany: row.receivablesAccountCompany,
      // vatNumber: row.vatNumber,
      // vatCompany: row.vatCompany,
    };
    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);
    }
  }
}

// 更新行任务保存按钮
const saveRowEvent = async (row: RowVO) => {
  //clearRowEvent(row)
  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 handleStatusChange(row) {
  const $grid = xGrid.value;
  if ($grid) {
    const updatedData = {
      id: row.id,
      status: row.status,
    };
    // 传partial=1,可只修改状态
    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);
    }
  }
}

// 创建任务
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,
    companyEnglishName: taskRuleForm.companyEnglishName,
    // address: taskRuleForm.address,
    juridicalPerson: taskRuleForm.juridicalPerson,
    department: taskRuleForm.department,
    // juridicalPersonCreditCard: taskRuleForm.juridicalPersonCreditCard,
    // juridicalPersonCreditCardAddress: taskRuleForm.juridicalPersonCreditCardAddress,
    // receivablesAccount: taskRuleForm.receivablesAccount,
    // receivablesAccountCompany: taskRuleForm.receivablesAccountCompany,
    // vatNumber: taskRuleForm.vatNumber,
    // vatCompany: taskRuleForm.vatCompany,
    user: taskRuleForm.operation,
    operater: [taskRuleForm.operater],
  };
  try {
    const resp = await postCreateTask(body);
    if (resp.code === 2000) {
      dialogFormVisible.value = false;
      taskRuleFormRef.value.resetFields();
      await getTaskList(); // 重新获取任务列表
      ElMessage({ message: '创建成功', type: 'success', });
    }
  } catch (error) {
    console.log('error:', 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();
    }
  });
};

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

//发送通知
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) {
    console.log('error:', error);
  }
}

// 导出接口
async function handleExport() {
  try {
    gridOptions.loading = true;
    const response = await exportTaskData(filter.value,);
    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('导出数据成功');
  } catch (error) {
    console.error('导出数据失败:', error);
  }
}

// 获取填写人下拉框
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 formItems = ref([
  { label: '平台编号', prop: 'number', type: 'input', placeholder: '请输入平台编号' },
  { label: '平台名称', prop: 'name', type: 'input', placeholder: '请输入平台名称' },
  { label: '国家', prop: 'country', type: 'input', placeholder: '请输入国家' },
  { label: '品牌', prop: 'brand', type: 'input', placeholder: '请输入品牌' },
  {
    label: '录入人员',
    prop: 'operation',
    type: 'select',
    placeholder: '请选择录入人员',
    multiple: true,
    collapseTags: true,
    collapseTagsTooltip: true,
    options: operationList
  },
  { label: '部门', prop: 'department', type: 'input', placeholder: '请输入部门' },
  { label: '运营', prop: 'operater', type: 'input', placeholder: '请输入运营' },
  {
    label: '平台币种',
    prop: 'currency',
    type: 'autocomplete',
    placeholder: '请输入平台币种',
    debounce: 100,
    fetchSuggestions: querySearch,
    triggerOnFocus: false,
    clearable: true,
    onSelect: handleSelect
  },
  {
    label: '回款/余额币种',
    prop: 'currencyCodePlatform',
    type: 'autocomplete',
    placeholder: '请输入回款/余额币种',
    debounce: 100,
    fetchSuggestions: querySearch,
    triggerOnFocus: false,
    clearable: true,
    onSelect: handleCurrencyCodePlatformSelect
  },
  { label: '平台', prop: 'platform', type: 'input', placeholder: '请输入平台' },
  { label: '线路', prop: 'line', type: 'input', placeholder: '请输入线路' },
  { label: 'IP地址', prop: 'ipaddress', type: 'input', placeholder: '请输入IP地址' },
  { label: '注册公司', prop: 'company', type: 'input', placeholder: '请输入注册公司' },
  { label: '公司英文名称', prop: 'companyEnglishName', type: 'input', placeholder: '请输入公司英文名称' },
  { label: '公司法人', prop: 'juridicalPerson', type: 'input', placeholder: '请输入公司法人' },

  // { label: '公司地址', prop: 'address', type: 'input', placeholder: '请输入公司地址' },
  // { label: '法人信用卡', prop: 'juridicalPersonCreditCard', type: 'input', placeholder: '请输入法人信用卡' },
  // { label: '信用卡地址', prop: 'juridicalPersonCreditCardAddress', type: 'input', placeholder: '请输入信用卡地址' },
  // { label: '收款账号', prop: 'receivablesAccount', type: 'input', placeholder: '请输入收款账号' },
  // { label: '收款账号公司', prop: 'receivablesAccountCompany', type: 'input', placeholder: '请输入收款账号公司' },
  // { label: 'VAT税号', prop: 'vatNumber', type: 'input', placeholder: '请输入VAT税号' },
  // { label: 'VAT税号公司名称', prop: 'vatCompany', type: 'input', placeholder: '请输入VAT税号公司名称' },
]);

// 表格样式
const cellStyle = () => {
  return {
    fontSize: '12px',
    fontWeight: '600',
    padding: 0,
  };
};

const headerCellStyle = () => {
  return {
    fontSize: '13px',
    backgroundColor: '#f0f1f3',
  };
};

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

</script>

<template>
  <div class="p-2.5">
    <el-card class="custom-card-style flex gap-1.5 justify-between" shadow="hover">
      <Selector ref="selectorRef" @update:filteredData="filteredDataChange" :show-company="true" />
    </el-card>
    <el-card class="my-3" shadow="hover">
      <vxe-grid ref="xGrid" :cell-style="cellStyle" :header-cell-style="headerCellStyle" stripe v-bind="gridOptions"
                v-on="gridEvents" @edit-actived="handleEditActived" @edit-closed="handleEditClosed">
        <template #toolbar_buttons>
          <el-button :icon="Plus" type="primary" text bg @click="dialogFormVisible = true"> 添加任务</el-button>
          <el-button :disabled="isDeleteDisabled" text bg :icon="Delete" plain type="danger" @click="removeEvent">删除
          </el-button>
          <el-button v-if="!isDeleteDisabled" plain text bg round type="success" @click="userDialogFormVisible =true">
            修改填写人
          </el-button>
        </template>
        <template #toolbar_tools>
          <div class="pr-2.5">
            <el-tooltip content="指定店铺发送通知" placement="top">
              <vxe-button v-if="!isDeleteDisabled" plain circle icon="vxe-icon-envelope" @click="noticeDialogFormVisible =true"></vxe-button>
            </el-tooltip>
            <el-tooltip content="保存" placement="top">
              <vxe-button circle icon="vxe-icon-save" @click="saveEvent"></vxe-button>
            </el-tooltip>
            <el-tooltip content="发送通知" placement="top">
              <el-dropdown style="padding: 0 10px;" trigger="click">
                <vxe-button circle icon="vxe-icon-bell"></vxe-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-tooltip>
            <el-tooltip content="下载表格" placement="top">
              <vxe-button circle icon="vxe-icon-download" @click="handleExport"></vxe-button>
            </el-tooltip>
          </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-tooltip content="编辑" placement="top">
              <el-button icon="Edit" type="text" @click="editRowEvent(row)"></el-button>
            </el-tooltip>
          </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 #department_edit="{ row }">
          <vxe-input v-model="row.department"></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
              size="small"
              @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>-->
          <vxe-select
              v-model="row.user"
              multiple
              filterable
              clearable
          >
            <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
              @blur="enableAutoExitEdit"
              @focus="disableAutoExitEdit"
              @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
              @blur="enableAutoExitEdit"
              @focus="disableAutoExitEdit"
              @select="item => handelRowCurrencyCodePlatformSelect(item,row)"
          >
            <template v-slot="{ item }">
              <div>{{ item }}</div>
            </template>
          </el-autocomplete>
        </template>
        <template #companyEnglishName_edit="{ row }">
          <vxe-input v-model="row.companyEnglishName"></vxe-input>
        </template>
        <template #juridicalPerson_edit="{ row }">
          <vxe-input v-model="row.juridicalPerson"></vxe-input>
        </template>
      </vxe-grid>
    </el-card>
  </div>
  <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-position="top"
        label-width="auto"
        status-icon
        style="max-width: 600px">
      <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px">
      <el-form-item
          v-for="(item, index) in formItems"
          :key="index"
          :label="item.label"
          :prop="item.prop"
      >
        <template v-if="item.type === 'input'">
          <el-input v-model="taskRuleForm[item.prop]" :placeholder="item.placeholder" />
        </template>
        <template v-else-if="item.type === 'select'">
          <el-select
              v-model="taskRuleForm[item.prop]"
              :collapse-tags="item.collapseTags"
              :collapse-tags-tooltip="item.collapseTagsTooltip"
              :multiple="item.multiple"
              :placeholder="item.placeholder"
          >
            <el-option
                v-for="option in item.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            ></el-option>
          </el-select>
        </template>
        <template v-else-if="item.type === 'autocomplete'">
          <el-autocomplete
              v-model="taskRuleForm[item.prop]"
              :clearable="item.clearable"
              :debounce="item.debounce"
              :fetch-suggestions="item.fetchSuggestions"
              :placeholder="item.placeholder"
              :trigger-on-focus="item.triggerOnFocus"
              @select="item.onSelect"
          >
            <template v-slot="{ item }">
              <div>{{ item }}</div>
            </template>
          </el-autocomplete>
        </template>
      </el-form-item>
      </div>
    </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>
  <el-dialog v-model="userDialogFormVisible" :before-close="updateUserCancel" align-center
             style="border-radius: 10px;" title="修改填写人" width="500">
    <div class="mb-3">
      <el-radio-group v-model="updateSelect">
        <el-radio :label="1">添加</el-radio>
        <el-radio :label="2">删除</el-radio>
      </el-radio-group>
    </div>
    <el-form-item align-center label="录入人员:" prop="operation" width="500">
      <el-select v-model="taskRuleForm.operation" collapse-tags collapse-tags-tooltip multiple filterable clearable
                 placeholder="请选择录入人员">
        <el-option v-for="item in operationList" :key="item.value" :label="item.label"
                   :value="item.value"></el-option>
      </el-select>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateUserCancel">取消</el-button>
        <el-button type="primary" @click="updateUser"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="noticeDialogFormVisible" align-center
             style="border-radius: 10px;" title="指定店铺发送通知" width="500">
    <el-form-item align-center label="消息内容:" width="500">
      <el-input v-model="noticeMessage" type="textarea"></el-input>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="noticePersonCancel">取消</el-button>
        <el-button type="primary" @click="noticePerson"> 确认</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;
}

:deep(.vxe-table--header .vxe-header--row th .vxe-cell,
.vxe-table--body .vxe-body--row td .vxe-cell) {
  padding-left: 0 !important;
  padding-right: 0 !important;
}
</style>
