<script setup lang="tsx">
import { nextTick, ref } from 'vue';
import { NButton, NDataTable, NInputNumber, NTag } from 'naive-ui';
import {
  fetchDeletePolicyFee,
  fetchGetgetStationInfoPageByEquipment,
  fetchgetPolicyFee,
  fetchsaveBatchPolicyFee
} from '@/service/api/operation/accounting-strategy';
import { fetchGegetPartyStationInfo } from '@/service/api/device/terminal-manage';
import { fetchGetChannelList } from '@/service/api/goods-center/store-goods';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import { useForm } from '@/components/zt/Form/hooks/useForm';
const optionsData = ref<Api.goods.Channel[]>([]);

const Columns: NaiveUI.TableColumn<Api.device.ThirdPartyStationInfoPageVO>[] = [
  {
    key: 'stationId',
    title: '充电站ID',
    align: 'center'
  },
  {
    key: 'stationName',
    title: '充电站名称',
    align: 'center'
  },
  {
    key: 'unitName',
    title: '单位名称',
    align: 'center'
  },
  {
    key: 'areaCode',
    title: '省市辖区编码',
    align: 'center'
  },
  {
    key: 'address',
    title: '详细地址',
    align: 'center'
  },
  {
    key: 'serviceTel',
    title: '服务电话',
    align: 'center'
  },
  {
    key: 'stationType',
    title: '站点类型',
    align: 'center',
    render: row => {
      return (
        <div>
          {row.stationType === 1 && <n-tag type="primary">公共</n-tag>}
          {row.stationType === 50 && <n-tag type="danger">个人</n-tag>}
          {row.stationType === 100 && <n-tag type="info">公交(专用)</n-tag>}
          {row.stationType === 101 && <n-tag type="primary">环卫(专用)</n-tag>}
          {row.stationType === 102 && <n-tag type="success">物流(专用)</n-tag>}
          {row.stationType === 103 && <n-tag type="warning">物流(专用)</n-tag>}
          {row.stationType === 255 && <n-tag type="info">物流(专用)</n-tag>}
        </div>
      );
    }
  },
  {
    key: 'stationStatus',
    title: '站点状态',
    align: 'center',
    render(rowData) {
      return (
        <div>
          {rowData.stationStatus === 0 && <n-tag type={'warning'}>未知</n-tag>}
          {rowData.stationStatus === 1 && <n-tag type={'danger'}>建设中</n-tag>}
          {rowData.stationStatus === 5 && <n-tag type={'info'}>关闭下线</n-tag>}
          {rowData.stationStatus === 6 && <n-tag type={'primary'}>维护中</n-tag>}
          {rowData.stationStatus === 50 && <n-tag type={'success'}>正常使用</n-tag>}
        </div>
      );
    }
  },
  {
    key: 'salesType',
    title: '收费类型',
    align: 'center',
    render: row => {
      return (
        <div>
          {row.salesType == 0 && <NTag type={'error'}>平台</NTag>}
          {row.salesType == 1 && <NTag type={'primary'}>企业</NTag>}
          {row.salesType == 2 && <NTag type={'warning'}>渠道方</NTag>}
        </div>
      );
    }
  }
];
const ModelColumns: NaiveUI.TableColumn<Api.device.ServiceRateConfig>[] = [
  {
    title: '规格信息（时段标志）',
    key: 'periodFlag',
    align: 'center',
    width: 200,
    render: row => {
      const arrText = ['尖', '峰', '平', '谷'];
      return arrText[row.periodFlag - 1];
    }
  },
  {
    title: '时段',
    key: 'timePeriod',
    align: 'center',
    width: 120
  },
  {
    title: '企业',
    key: 'periodFlag',
    align: 'center',
    width: 200,
    render: row => {
      if (!row.channelCDVOS) return '--';
      if (!row.channelCDVOS.length) return '--';
      return row.channelCDVOS.map(it => {
        return <div>{it.channelName}</div>;
      });
    }
  },
  {
    title: '电费（元/度）',
    key: 'electricityPrice',
    align: 'center',
    width: 120,
    render: row => {
      if (!row.channelCDVOS) return row.electricityPrice;
      if (!row.channelCDVOS.length) return row.electricityPrice;
      return row.channelCDVOS.map(it => {
        return <div class={'mt10px'}>{it.electricityPrice}</div>;
      });
    }
  },
  {
    title: '结算服务费（元）',
    key: 'settlementServiceFee',
    align: 'center',
    width: 120,
    render: row => {
      if (!row.channelCDVOS) return row.settlementServiceFee;
      if (!row.channelCDVOS.length) return row.settlementServiceFee;
      return row.channelCDVOS.map(it => {
        return <div class={'mt10px'}>{it.settlementServiceFee}</div>;
      });
    }
  },
  {
    title: '结算费合计（元/度） ',
    key: 'settlementTotalPrice',
    align: 'center',
    width: 120,
    render: row => {
      if (!row.channelCDVOS) return row.settlementTotalPrice;
      if (!row.channelCDVOS.length) return row.settlementTotalPrice;
      return row.channelCDVOS.map(it => {
        return <div class={'mt10px'}>{it.settlementTotalPrice}</div>;
      });
    }
  },
  {
    title: '运营服务费（元） ',
    key: 'opFee',
    align: 'center',
    width: 120,
    render: row => {
      if (!row.channelCDVOS) return row.opFee;
      if (!row.channelCDVOS.length) return row.opFee;
      return row.channelCDVOS.map(it => {
        return (
          <div class={'mt10px'}>
            <NInputNumber
              precision={2}
              step={0.01}
              value={it.opFee}
              onUpdate:value={val => (it.opFee = val)}
              min={0}
            ></NInputNumber>
          </div>
        );
      });
    }
  },
  {
    title: '销售合计价格（元/度） ',
    key: 'saleTotalPrice',
    align: 'center',
    width: 120,
    render: row => {
      if (!row.channelCDVOS) return row.saleTotalPrice;
      if (!row.channelCDVOS.length) return row.saleTotalPrice;
      return row.channelCDVOS.map(it => {
        return <div class={'mt10px'}>{(it.settlementTotalPrice * 100 + Number(it.opFee) * 100) / 100}</div>;
      });
    }
  }
];

const [registerTable] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'stationId',
        label: '充电站ID',
        component: 'NInput'
      },
      {
        field: 'stationName',
        label: '充电站名称',
        component: 'NInput'
      },
      {
        field: 'stationStatus',
        label: '站点状态',
        component: 'NSelect',
        componentProps: {
          options: [
            {
              label: '未知',
              value: 0
            },
            {
              label: '建设中',
              value: 1
            },
            {
              label: '关闭下线',
              value: 5
            },
            {
              label: '维护中',
              value: 6
            },
            {
              label: '正常使用',
              value: 50
            }
          ]
        }
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '计费策略',
    showAddButton: true
  }
});
const [registerModal, { openModal, setModalLoading, setSubLoading, closeModal }] = useModal({
  title: '',
  width: 1400,
  height: 800
});
const [registerForm, { getFieldsValue, setFieldsValue, validate }] = useForm({
  schemas: [
    {
      field: 'stationId',
      label: '选择电站',
      component: 'ApiSelect',
      componentProps: {
        api: fetchGegetPartyStationInfo,
        labelField: 'stationName',
        valueField: 'id'
      },
      required: true
    },
    {
      field: 'salesType',
      label: '收费类型',
      component: 'NRadioGroup',
      componentProps: {
        options: [
          {
            label: '企业',
            value: 1
          },
          {
            label: '渠道方',
            value: 2
          },
          {
            label: '平台',
            value: 0
          }
        ]
      },
      defaultValue: 1,
      required: true
    },
    {
      label: '选择企业',
      field: 'channelPartyId',
      component: 'ApiSelect',
      componentProps: {
        api: fetchGetChannelList,
        labelFeild: 'channelName',
        valueFeild: 'id',
        multiple: true,
        onUpdateValue: (value: number[]) => {
          console.log(value, '=====');

          handleSetTabData(value);
        },
        getOptions(options) {
          optionsData.value = options;
        }
      },
      required: true,
      ifShow: schema => {
        return schema.model.salesType === 1;
      }
    },
    // {
    //   field: 'stationFee',
    //   label: '整站设置统一服务费',
    //   component: 'NInput',
    //   render({ model, field }) {
    //     return (
    //       <div class={'flex items-center'}>
    //         <div class={'w300px'}>
    //           <NInput value={model[field]} placeholder={'请输入整站设置统一服务费'}></NInput>
    //         </div>
    //         <div class={'ml20px'}>
    //           <NButton>确定</NButton>
    //         </div>
    //       </div>
    //     );
    //   }
    // },
    {
      field: 'policyFees',
      label: '服务费设置',
      component: 'NInput',
      render: ({ model, field }) => {
        return <NDataTable columns={ModelColumns} data={model[field]}></NDataTable>;
      }
    }
  ],
  labelWidth: 100,
  layout: 'horizontal',
  gridProps: {
    cols: '1',
    itemResponsive: true
  },
  collapsedRows: 1,
  showActionButtonGroup: false
});
const initFirmIds = ref<number[]>([]);
async function getModelTableList() {
  const model = await getFieldsValue();
  const { data, error } = await fetchgetPolicyFee({ ...model });
  if (!error) {
    const channelIds = data[0].channelCDVOS ? data[0].channelCDVOS.map(it => it.firmId) : [];
    initFirmIds.value = channelIds;
    await setFieldsValue({
      channelPartyId: channelIds,
      policyFees: data.map(it => {
        it.timePeriod = formatTime(it.timePeriod);
        it.opFee = it.operationServiceFee;
        it.channelCDVOS = it.channelCDVOS
          ? it.channelCDVOS.map(its => {
              return {
                ...its,
                electricityPrice: it.electricityPrice,
                settlementServiceFee: it.settlementServiceFee,
                settlementTotalPrice: it.settlementTotalPrice
              };
            })
          : [];
        return it;
      })
    });
  }
}

async function handleEidt(row: Api.device.ThirdPartyStationInfoPageVO) {
  setModalLoading(true);
  openModal();
  console.log(row, 'salesType');

  nextTick(async () => {
    await setFieldsValue({ stationId: row.id });
    await getModelTableList();
    setModalLoading(false);
  });
}
function formatTime(timeStr: string): string {
  if (timeStr.length !== 6) {
    throw new Error('时间格式不正确，应为6位数字');
  }

  return timeStr.replace(/(\d{2})(\d{2})(\d{2})/, '$1:$2:$3');
}
async function handleSetTabData(values: number[]) {
  const modelData = getFieldsValue();
  const tableDATA = modelData.policyFees || [];
  const newTableData = tableDATA.map((it: Api.device.ServiceRateConfig) => {
    return {
      ...it,
      channelCDVOS: values.map(channel => {
        const findData = optionsData.value.find(channels => channels.id == channel);
        if (!findData) {
          return {};
        }
        return {
          firmId: findData.id,
          channelName: findData.channelName,
          opFee: it.operationServiceFee,
          electricityPrice: it.electricityPrice,
          saleTotalPrice: it.saleTotalPrice,
          settlementTotalPrice: it.settlementTotalPrice,
          settlementServiceFee: it.settlementServiceFee
        };
      })
    };
  });
  setFieldsValue({ policyFees: newTableData });
}
async function handleSubmit() {
  await validate();
  setSubLoading(true);
  const modelData = getFieldsValue();
  const tableData = modelData.policyFees.map((it: Api.device.ServiceRateConfig) => {
    return {
      stationInfoId: modelData.stationId,
      periodFlag: it.periodFlag,
      channelCDVOS: it.channelCDVOS.map(channel => {
        return {
          firmId: channel.firmId,
          channelName: channel.channelName,
          opFee: channel.opFee
        };
      })
    };
  });
  const nowFirmIds = modelData.channelPartyId;
  const delids = initFirmIds.value.filter(it => !nowFirmIds.includes(it));
  console.log(delids, '删除ids============');
  try {
    await fetchsaveBatchPolicyFee(tableData);
    if (delids.length) {
      const updatePolicyFeeFroms = delids.map(it => {
        return {
          firmId: it,
          stationInfoId: modelData.stationId
        };
      });
      await fetchDeletePolicyFee(updatePolicyFeeFroms);
    }
    closeModal();
  } catch {
    setSubLoading(false);
  }
}
</script>

<template>
  <LayoutTable>
    <ZTable
      :columns="Columns"
      :immediate="true"
      :api="fetchGetgetStationInfoPageByEquipment"
      @register="registerTable"
      @add="openModal"
    >
      <template #op="{ row }">
        <NButton size="small" ghost type="primary" @click="handleEidt(row)">编辑</NButton>
      </template>
    </ZTable>
    <BasicModal @register="registerModal" @ok="handleSubmit">
      <BasicForm @register-form="registerForm"></BasicForm>
    </BasicModal>
  </LayoutTable>
</template>

<style scoped></style>
