<template>
  <div class="index-container" style="height: 100%">
    <div style="margin-bottom: 10px; text-align: right">
      <a-button v-if="historicalWeeklyRef === 0" @click="historicalWeekly" size="large" shape="round" type="primary">
        历史周报
      </a-button>
      <a-button v-if="historicalWeeklyRef === 1" @click="historicalWeeklyRef = 0" size="large" shape="round"
        type="primary">
        返回主页
      </a-button>
    </div>
    <div v-if="historicalWeeklyRef === 0" style="max-height: 80vh" class="overflow-auto">
      <div v-for="(row, rowIdx) in state.pageData" :key="rowIdx" class="items-center fl-mb-lg color-white row"
        style="min-height: 40px">
        <div class="items-center justify-between theme-bg col-12 row fl-px-md" style="min-height: 40px"
          :style="{ borderRadius: '8px 8px 0 0' }">
          <div class="col-3" style="display: flex; justify-content: space-between; flex-grow: 1">
            <div style="display: flex; align-items: center">
              时间<span class="fl-ml-lg">
                <a-date-picker v-if="!row.isStartDate" @change="(e) => {
                  panelChange(e, rowIdx, 'startDate', row);
                }
                  " valueFormat="YYYY-MM-DD" :allowClear="false" :value="row.startDate" />
                <span v-if="row.isStartDate">{{ row.startDate }}</span>
                ~
                <template v-if="Array.isArray(row.dateDue) && row.dateDue[0]">
                  <a-date-picker @change="(e) => {
                    panelChange(e, rowIdx, 'endDate', row);
                  }
                    " valueFormat="YYYY-MM-DD" :allowClear="false" :value="row.endDate" />
                </template>
                <template v-else>请先选择本次业务时间</template></span>
            </div>
            <div style="display: flex; align-items: center">
              {{
                uni.find((item) => item.DepartmentId === row.departmentId)
                  ?.DepartmentName
              }}
            </div>
            <div>
              到期金额时间区间<span class="fl-ml-lg"><a-range-picker :allowClear="false" @change="(e) => {
                changeRange(e, rowIdx);
              }
                " :value="row.dateDue" valueFormat="YYYY-MM-DD" /></span>
            </div>
          </div>
        </div>
        <div style="border-radius: 0 0 8px 8px" class="col-12 row">
          <fl-simple-table :fatherData="row" :config="state.tableConfig" :refreshCount="state.tableConfig.refreshCount"
            tableType="" :tableData="row.data || []" @triggerRowActions="handleRowActions">
          </fl-simple-table>
        </div>
        <div class="text-right col-12 fl-px-md" style="min-height: 40px; line-height: 40px; background: #e0dee6"
          :style="{ borderRadius: '0 0 8px 8px' }">
          <a-button @click="sending(rowIdx)" v-if="state.pageData[rowIdx].endDate" shape="round" type="primary">
            发送
          </a-button>
        </div>
      </div>
    </div>

    <div v-if="historicalWeeklyRef === 1">
      <div style="max-height: 80vh" class="overflow-auto">
        <div v-for="(row, rowIdx) in historicalData" :key="rowIdx" class="items-center fl-mb-lg color-white row"
          style="min-height: 40px">
          <div class="items-center justify-between bg-764CF6 col-12 row fl-px-md" style="min-height: 40px"
            :style="{ borderRadius: '8px 8px 0 0' }">
            <div class="col-3" style="
                display: flex;
                justify-content: space-between;
                flex-grow: 1;
              ">
              <div style="display: flex; align-items: center">
                时间<span class="fl-ml-lg">
                  {{ row.StartDate }}
                  ~ {{ row.EndDate }}</span>
              </div>
              <div style="display: flex; align-items: center">
                {{ row.Site }}
              </div>
              <div>
                到期金额时间区间<span class="fl-ml-lg">
                  {{ row.startDateDue }} ~ {{ row.endDateDue }}</span>
              </div>
            </div>
          </div>
          <div style="border-radius: 0 0 8px 8px" class="col-12 row">
            <fl-simple-table :fatherData="row" :config="state.tableConfig"
              :refreshCount="state.tableConfig.refreshCount" tableType="" :tableData="row.ReportUsers || []"
              @triggerRowActions="handleRowActions">
            </fl-simple-table>
          </div>
          <div class="text-right col-12 fl-px-md" style="min-height: 40px; line-height: 40px; background: #e0dee6"
            :style="{ borderRadius: '0 0 8px 8px' }">
            <a-button v-if="row.Status === 5" type="primary" shape="round" class="fl-mx-xs" style="min-width: 131px"
              @click="handleSure(row)">
              确认
            </a-button>
            <span v-if="row.Status === 4" class="fl-mx-lg color-black">已确认</span>
          </div>
        </div>
      </div>
      <div style="text-align: right">
        <a-pagination hideOnSinglePage @change="changePage" show-size-changer :page-size-options="['3', '5', '10']"
          v-model:current="currentPage" v-model:pageSize="pageSize" :total="countPage"
          @showSizeChange="onShowSizeChange" />
      </div>
    </div>
  </div>
</template>
<script setup>
import { Local, Session } from "@/utils/storage.js";
import { UpOutlined, DownOutlined } from "@ant-design/icons-vue";
import {
  ref,
  reactive,
  onBeforeMount,
  onMounted,
  getCurrentInstance,
  watch,
} from "vue";
import { message, Modal } from "ant-design-vue";
import { createVNode, defineComponent } from "vue";
import dayjs from "dayjs";

const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;
import flFormItem from "@/components/layout/form/formItem.vue";
import flSimpleTable from "@/components/layout/table/simpleTable.vue";
import { processError, processSuccess } from "@/utils/helper/message";
import { getParamsByObj } from "@/utils/helper/form";

const pageSize = ref(3);
const currentPage = ref(1);
const historicalWeeklyRef = ref(0);
const changeRange = (data, rowIdx) => {
  if (data) {
    Modal.confirm({
      title: () =>
        `您选择的时间区间为：${data?.join("至")}。是否确认继续操作？`,
      onOk() {
        state.pageData[rowIdx].dateDue = data;
        let promises = [];
        promises.push(createData(rowIdx));
        getAllPromise(promises);
      },
      onCancel() { },
      class: "test",
    });
  }
};
const onShowSizeChange = (current, pageSize) => { };
const sending = (i) => {
  const time1 = dayjs(state.pageData[i].startDate, "YYYY-MM-DD");
  const time2 = dayjs(state.pageData[i].endDate, "YYYY-MM-DD");
  if (!time1.isBefore(time2) && !time1.isSame(time2)) {
    message.warning("结束时间不能大于开始时间！请重新选择");
    return;
  }
  const data = {
    startDate: state.pageData[i].startDate,
    endDate: state.pageData[i].endDate,
    departmentName: uni.value[i].DepartmentName,
    departmentId: uni.value[i].DepartmentId,
    startDateDue: state.pageData[i].dateDue[0],
    endDateDue: state.pageData[i].dateDue[1],
  };
  $request.HTTP.components
    .postDataByParams("/report/create", data)
    .then((res) => {
      if (res.code === 200) {
        state.pageData[i].startDate = "";
        state.pageData[i].endDate = "";
        state.pageData[i].dateDue = [];
        uni.value.forEach((x, i) => {
          let promises = [];
          promises.push(createData(i));
          getAllPromise(promises);
        });
        message.success("发送成功");
      } else {
        message.warning(res.msg);
      }
    });
};
const panelChange = (value, rowIdx, prop, row) => {
  if (prop === "startDate") {
    Modal.confirm({
      title: () => `您选择的日期为：${value}。是否确认继续操作？`,
      onOk() {
        state.pageData[rowIdx][prop] = value;
        let promises = [];
        promises.push(createData(rowIdx));
        getAllPromise(promises);
      },
      onCancel() {
        if (!state.pageData[rowIdx][prop]) {
          state.pageData[rowIdx][prop] = undefined;
        }
      },
      class: "test",
    });
  }
  if (
    prop === "endDate" &&
    (state.pageData[rowIdx].dateDue?.length !== 2 ||
      !state.pageData[rowIdx].dateDue[0])
  ) {
    Modal.confirm({
      title: () => `请先确认周报到期金额字段的时间区间`,
      onOk() {
        state.pageData[rowIdx][prop] = "";
      },
      onCancel() { },
      class: "test",
    });
  } else if (
    prop === "endDate" &&
    state.pageData[rowIdx].dateDue?.length === 2 &&
    state.pageData[rowIdx].dateDue[0] &&
    state.pageData[rowIdx].dateDue[1]
  ) {
    Modal.confirm({
      title: () => `您选择的日期为：${value}。是否确认继续操作？`,
      onOk() {
        state.pageData[rowIdx][prop] = value;
        let promises = [];
        promises.push(createData(rowIdx));
        getAllPromise(promises);
      },
      onCancel() { },
      class: "test",
    });
  }
};
const historicalData = ref({});
const changePage = (value, valu2) => {
  historicalWeekly();
};
const countPage = ref(0);
const historicalWeekly = () => {
  const data = {
    Page: currentPage.value,
    PageSize: pageSize.value,
    StartDate: "",
    EndDate: "",
    Key: "",
    siteIds: uni.value.map((x) => Number(x.DepartmentId)),
  };
  $request.HTTP.components
    .postDataByParams("/report/my/list", data)
    .then((res) => {
      if (res.code === 200) {
        countPage.value = res.data.Count;
        historicalData.value = res.data.Data;
      }
    });
  historicalWeeklyRef.value = 1;
};
const maturityAmountTimeInterval = ref([]);
const state = reactive({
  searchData: {
    Status: [],
  },
  btnLoading: false,
  tableConfig: {
    tableClass: "no-radius no-shadow no-margin",
    rowKey: "ID",
    size: "small",
    refreshCount: 0,
    columns: [
      {
        title: "销售员",
        field: "SellerName",
      },
      {
        title: "当次业务",
        field: "Amount",
      },
      {
        title: "到期金额",
        field: "DueAmount",
        // rowEdit: {
        //   fatherData: true,
        //   show: "[%=Status%]===3",
        //   type: "input",
        // },
      },
      {
        title: "递增金额",
        field: "IncreaseAmount",
      },
      {
        type: "select",
        title: "业绩健康码",
        field: "Color",
        options: [
          { label: "绿", value: "green", class: "color-info" },
          { label: "黄", value: "yellow", class: "color-yellow" },
          { label: "红", value: "red", class: "color-danger" },
          { label: "新站点", value: "newValue", class: "color-danger" },
        ],
      },
    ],
  },
  pageData: [],
});
//查询周报日期
const userInfo = Local.get("userInfo");
const createData = (i) => {
  return new Promise((resolve) => {
    const data = {
      startDateDue:
        Array.isArray(state.pageData[i].dateDue) &&
          state.pageData[i].dateDue.length === 2
          ? state.pageData[i].dateDue[0]
          : "",
      endDateDue:
        Array.isArray(state.pageData[i].dateDue) &&
          state.pageData[i].dateDue.length === 2
          ? state.pageData[i].dateDue[1]
          : "",
      startDate: state.pageData[i].startDate,
      endDate: state.pageData[i].endDate,
      departmentName: !uni.value.length
        ? uniqueData.value[i].DepartmentName
        : uni.value[i].DepartmentName,
      departmentId: !uni.value.length
        ? uniqueData.value[i].DepartmentId
        : uni.value[i].DepartmentId,
      pageSize: 9999,
      page: 1,
    };
    $request.HTTP.components
      .postDataByParams("/report/create/before", data)
      .then((res) => {
        resolve(res.data, i);
      });
  });
};
const uniqueData = ref([]);
const uni = ref([]);
const getData = () => {
  const uniqueDepartmentIds = new Set(
    userInfo.PositionUsers.map((item) => item.DepartmentId)
  );
  uniqueData.value = Array.from(uniqueDepartmentIds).map((deptId) => {
    const originalItem = userInfo.PositionUsers.find(
      (item) => item.DepartmentId === deptId
    );
    return originalItem;
  });
  let promises = [];
  uniqueData.value.forEach((x, i) => {
    state.pageData.push({});
    promises.push(createData(i));
    getAllPromise(promises, "once");
  });
};
const getAllPromise = (promises, type = null) => {
  Promise.all(promises)
    .then((res) => {
      const list = res.filter(Boolean);
      if (list.length) {
        list.forEach((item, index) => {
          if (item) {
            if (type === "once") {
              state.pageData[index] = item || {};
              if (item.startDate) {
                state.pageData[index].isStartDate = true;
              }
              state.pageData[index].dateDue = [
                item.startDateDue,
                item.endDateDue,
              ];
              state.pageData[index].departmentId = item.departmentId;
              state.pageData = state.pageData.filter(
                (n) => Object.keys(n).length
              );
              const departmentIds = list.map((item) => item.departmentId);
              uni.value = uniqueData.value.filter((item) =>
                departmentIds.includes(item.DepartmentId)
              );
            } else {
              state.pageData.forEach((n, i) => {
                if (n.departmentId === item.departmentId) {
                  state.pageData[i] = item;
                  if (n.startDate) {
                    state.pageData[i].isStartDate = true;
                  }
                  state.pageData[i].dateDue = [
                    item.startDateDue,
                    item.endDateDue,
                  ];
                }
              });
            }
          }
        });
      } else {
        state.pageData = [];
      }
    })
    .catch((error) => { });
};
onBeforeMount(() => {
  getData();
  // getPageData();
});

onMounted(() => { });
const emits = defineEmits(["triggerClick"]);

const getPageData = () => {
  let url = "seller/report/cashier/list";
  let params = state.searchData;
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (res.status === 0) {
        state.pageData = res.data.Data || [];
      }
    },
    () => { }
  );
};
const handleRowActions = (btnConfig, rowData, fatherData) => {
  if (btnConfig.actionType === "sure_btn") {
    let url = "seller/order/cashier/sure";
    let params = { ID: rowData.ID };
    $request.HTTP.components.postDataByParams(url, params).then(
      (res) => {
        if (res.status === 0) {
          let url = "seller/transaction/cashier/detail";
          let params = { ID: fatherData.ID };
          $request.HTTP.components.postDataByParams(url, params).then(
            (res) => {
              if (res.status === 0) {
                for (let i in state.pageData) {
                  let item = state.pageData[i];
                  if ((item.ID = fatherData.ID)) {
                    item.Orders = res.data.Orders;
                    break;
                  }
                }
              } else {
                processError(res.msg);
              }
            },
            () => { }
          );
        } else {
          processError(res.msg);
        }
      },
      () => { }
    );
  }
};
const handleChange = (val, field) => {
  state.searchData.Status = val;
  getPageData();
};
const handleClick = (val) => {
  emits("triggerClick", val);
};
onMounted(() => { });
const handleCalc = (val) => {
  let url = "seller/reportuser/batch/update";
  let params = { ID: val.ID, Data: val.ReportUsers };
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (res.status === 0) {
        getPageData();
      } else {
        processError(res.msg);
      }
    },
    () => { }
  );
};

const handleReset = (val) => {
  let url = "seller/report/cashier/re";
  let params = { ID: val.ID };
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (res.status === 0) {
        getPageData();
      } else {
        processError(res.msg);
      }
    },
    () => { }
  );
};
const handleSure = (val) => {
  let url = "seller/report/cashier/sure";
  let params = { ID: val.ID };
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (res.status === 0) {
        getPageData();
      } else {
        processError(res.msg);
      }
    },
    () => { }
  );
};
</script>
<style lang="scss" scoped>
:deep(.ant-table-tbody .ant-table-row.ant-table-row-level-0:last-child td) {
  background: $theme-primary;
  color: #fff;
}

:deep(.ant-table-tbody .ant-table-row.ant-table-row-level-0:last-child td:hover) {
  background: $theme-primary;
  color: #fff;
}

.my-search {
  display: flex;
  align-items: center;
  margin-bottom: 0px;

  .icon {
    width: 22px;
    height: 20px;
  }

  .search-input {
    width: 576px;
    height: 35px;
    border-radius: 20px;
    color: #fff !important;
  }

  .ant-input-affix-wrapper {
    background: rgba($color: #777777, $alpha: 0.4) !important;
    border: none !important;
    box-shadow: none;
    color: #fff;

    :deep(.ant-input) {
      background: transparent;
    }
  }

  .ant-input-affix-wrapper:hover,
  .ant-input-affix-wrapper:focus {
    border: none !important;
    box-shadow: none;
  }

  .ant-input-affix-wrapper:not(.ant-input-affix-wrapper-disabled):hover {
    border: none !important;
    box-shadow: none;
  }

  .ant-input:focus {
    /* 去除获取焦点时的样式 */
    border: none;
    box-shadow: none;
  }

  .ant-input {
    /* 去除边框样式 */
    resize: none;
    border: none;
    color: #ffffff;
  }

  input {
    background: transparent;
  }

  ::-webkit-input-placeholder {
    color: #ffffff !important;
  }

  :-moz-placeholder {
    /* Firefox 18- */
    color: #ffffff !important;
  }

  ::-moz-placeholder {
    /* Firefox 19+ */
    color: #ffffff !important;
  }

  :-ms-input-placeholder {
    color: #ffffff !important;
  }

  .search-btn {
    width: 75px;
    height: 35px;
    line-height: 35px;
    text-align: center;
    margin-left: 15px;
    background: #c1b2e5;
    color: #ffffff;
    border-radius: 20px;
    padding: 0;
    border: none;
    font-size: 14px;
    font-family: "苹方-简";
  }
}
</style>
