<template>
  <div class="p-4">
    <a-card :bordered="false" style="height: 100%">
      <a-row>
        <a-col :span="21">
          <a-radio-group v-model:value="parmas.type" @change="changeType">
            <a-radio-button value="1">当天</a-radio-button>
            <a-radio-button value="2">近3天</a-radio-button>
            <a-radio-button value="3">近7天</a-radio-button>
            <a-radio-button value="4">近30天</a-radio-button>
            <a-radio-button value="5">自定义</a-radio-button>
          </a-radio-group>
          <span v-show="parmas.type == '5'" style="margin-left: 5px;">
            <a-range-picker :value-format="valueFormat" @change="changeDate" />
          </span>
          <a-select ref="select" placeholder="请选区域" v-model:value="parmas.housingestateId"
            style="width: 200px;margin-left: 5px;" @change="handleHousinges">
            <a-select-option value="">全部</a-select-option>
            <a-select-option :value="item.housingestateId" v-for="item in housingestates" :key="item.housingestateId">{{item.housingestateName }}</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="21" v-show="izList">
          <a-form layout="inline" :model="parmas" :labelCol="{ style: { width: 'auto', paddingRight: '90px' } }"
            :wrapperCol="{ style: { display: 'flex', alignItems: 'center' } }">
            <a-form-item label="投递重量">
              <a-input-number v-model:value="parmas.countMin" placeholder="最小次数" :min="0" />
              <span class="ant-form-text" style="margin: 0 8px;">至</span>
              <a-input-number v-model:value="parmas.countMax" placeholder="最大次数" :min="0" />
            </a-form-item>
          </a-form>
          <a-button type="link" @click="loadListDate">查询</a-button>
          <a-button type="link" @click="resetListData">重置</a-button>
        </a-col>
        <a-col :span="3">
          <a-radio-group v-model:value="izList" button-style="solid">
            <a-radio-button :value="false">统计图</a-radio-button>
            <a-radio-button :value="true">列表页</a-radio-button>
          </a-radio-group>
        </a-col>
      </a-row>
      <Bar v-show="!izList" :chartData="dataSource" height="80vh"
        :option="{ title: { text: '设备投递重量排行榜', left: 'center' } }"
        :itemStyle="{ normal: { label: { show: true, position: 'top' } } }"
        :axisLabel="{ rotate: 45}"
        :seriesName="'投递重量'"></Bar>
      <a-table v-show="izList" :dataSource="tableData" :columns="columns">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="handleView(record)">查看</a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 查看详情弹窗 -->
    <a-modal v-model:visible="detailVisible" title="会员投递详情" width="80%" :footer="null">
      <a-table :dataSource="detailData" :columns="detailColumns" rowKey="phone">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleMark(record)">标记</a-button>
              <a-button type="link" danger @click="handleBlock(record)">屏蔽</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, unref, reactive, onMounted } from 'vue';
import Bar from '/@/components/chart/Bar.vue';
import { tdzlList, allTdcsList, housingestateList, queryHyjlList } from '../shebei.api';

const valueFormat = 'YYYY-MM-DD';
const dataSource = ref([]);
const dateValue = ref();
const housingestates = ref();
const izList = ref(false)
const tableData = ref([])
const detailVisible = ref(false);
const detailData = ref([]);

const columns = ref([
  {
    title: '会员',
    dataIndex: 'name',
    key: 'name',
    align: 'center'
  },
  {
    title: '投递次数',
    dataIndex: 'value',
    key: 'value',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: '150px',
  }
])

const detailColumns = ref([
  {
    title: '会员手机号',
    dataIndex: 'phone',
    key: 'phone',
    align: 'center'
  },
  {
    title: '金额',
    dataIndex: 'money',
    key: 'money',
    align: 'center'
  },
  {
    title: '重量',
    dataIndex: 'weight',
    key: 'weight',
    align: 'center'
  },
  {
    title: '投递时间',
    dataIndex: 'addTime',
    key: 'addTime',
    align: 'center'
  },
  {
    title: '订单是否有效',
    dataIndex: 'invalid',
    key: 'invalid',
    align: 'center'
  },
  {
    title: '订单开始重量',
    dataIndex: 'startWeight',
    key: 'startWeight',
    align: 'center'
  },
  {
    title: '订单结束重量',
    dataIndex: 'endWeight',
    key: 'endWeight',
    align: 'center'
  },
  {
    title: '厂家更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    align: 'center'
  },
  {
    title: '扣除金额',
    dataIndex: 'deductMoney',
    key: 'deductMoney',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: '200px',
  }
]);

async function getHousingestates() {
  housingestates.value = await housingestateList();
}

const parmas = reactive<any>({
  beginTime: '',
  endTime: '',
  type: '1',
  countMin: null,
  countMax: null,
})

function changeType() {
  parmas.endTime = getPreviousDate(0) + ' 23:59:59';
  if (parmas.type === '1') {
    parmas.beginTime = getPreviousDate(0) + ' 00:00:00';
    loadDate();
  }
  if (parmas.type === '2') {
    parmas.beginTime = getPreviousDate(2) + ' 00:00:00';
    loadDate();
  }
  if (parmas.type === '3') {
    parmas.beginTime = getPreviousDate(6) + ' 00:00:00';
    loadDate();
  }
  if (parmas.type === '4') {
    parmas.beginTime = getPreviousDate(29) + ' 00:00:00';
    loadDate();
  }
}

const changeDate = (date, dateString) => {
  parmas.beginTime = dateString[0] + ' 00:00:00';
  parmas.endTime = dateString[1] + ' 23:59:59';
  loadDate();
};

function handleHousinges() {
  loadDate();
};

async function loadDate() {
  const res = await tdzlList(parmas);
  dataSource.value = [];
  for (let i = 0; i < res.length; i++) {
    let name = res[i].imei;
    if(res[i].housingestateName!=null&&res[i].content!=null){
      name = res[i].housingestateName+'-'+res[i].content;
    }
    dataSource.value.push({
      name: `${name}`,
      value: res[i].weight,
    });
  }
}

async function loadListDate() {
  const res = await allTdcsList(parmas);
  tableData.value = [];
  for (let i = 0; i < res.length; i++) {
    tableData.value.push({
      name: `${res[i].imei}`,
      value: res[i].cn,
    });
  }
}

//重置
function resetListData() {
  parmas.countMin = null
  parmas.countMax = null
  loadListDate()
}

// 查看详情
const handleView = async (record) => {
  try {
    const res = await queryHyjlList({ phone: record.name });
    detailData.value = res;
    detailVisible.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
  }
};

function getPreviousDate(days) {
  const date = new Date();
  date.setDate(date.getDate() - days);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份+1（0-indexed）并补零
  const day = String(date.getDate()).padStart(2, '0');         // 日期补零
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate;
}

// 新增的方法
const handleMark = (record) => {
  console.log('标记记录:', record);
  // 这里可以添加标记逻辑，如调用API等
  // 示例: markRecord(record.phone);
};

const handleBlock = (record) => {
  console.log('屏蔽记录:', record);
  // 这里可以添加屏蔽逻辑，如调用API等
  // 示例: blockRecord(record.phone);
};


onMounted(() => {
  if (parmas.type == '1') {
    parmas.beginTime = getPreviousDate(0) + ' 00:00:00';
    parmas.endTime = getPreviousDate(0) + ' 23:59:59';
  }
  loadDate();
  loadListDate();
  getHousingestates();
})

</script>
