<template>
  <a-spin
    :spinning="spinning"
    :tip="tipContent"
  >
    <a-divider orientation="left">开关配置</a-divider>
    <SwitchConfigForm></SwitchConfigForm>
    <a-divider orientation="left">运营配置</a-divider>
    <OperateConfigForm></OperateConfigForm>
    <a-divider orientation="left">用车配置</a-divider>
    <UseCarConfigForm></UseCarConfigForm>
    <a-divider orientation="left">锁车配置</a-divider>
    <LockCarConfigForm></LockCarConfigForm>
    <a-divider orientation="left">还车配置</a-divider>
    <ReturnCarConfigForm></ReturnCarConfigForm>
    <a-divider orientation="left">客服配置</a-divider>
    <CustomerServiceConfigForm></CustomerServiceConfigForm>
  </a-spin>
</template>

<style scoped>
.a-tabs-card {
  position: relative;
}
</style>
<script setup>
import { ref, defineProps } from 'vue'
import { callOperate } from '@/apis/call.js'
import { message } from 'ant-design-vue'
import { getGUID } from '@/utils/tools';
import _ from 'lodash'
import SwitchConfigForm from './SwitchConfigForm.vue';
import UseCarConfigForm from './UseCarConfigForm.vue';
import LockCarConfigForm from './LockCarConfigForm.vue';
import ReturnCarConfigForm from './ReturnCarConfigForm.vue';
import CustomerServiceConfigForm from './CustomerServiceConfigForm.vue';
import OperateConfigForm from './OperateConfigForm.vue';


const props = defineProps({
  onCallBack: {
    type: Function,
    required: true
  },
});

const formRef = ref();
const spinning = ref(false);
const tipContent = ref("加载中...");
const freeDuration = ref("免费时长(分钟)");
const deteilShow = ref(false);
const isAdd = ref(true);
const warmReminder = ref("");
const field = ref("");

const form = ref({
  costConfigId: "",
  regionId: "",
  chargingMode: "",
  freeDurationMode: "1",
  freeDuration: "",
  timeDivisionCharging: "1",
  ebikeSysRcostsetTimePeriodDtos: [],
  ebikeSysRcostsetWeekDtos: [],
  startupCost: "",
  startupDuration: "",
  durationCost: "",
  duration: "",
  dispatchFeeOutOperateArea: "",
  dispatchFeeBanArea: "",
  parkingAreaOutDispatchFee: "",
  helmetManagementFee: "",
  cappedAmount: "",
  shortRentAdvance: "",
  whetherOpenLongRent: ""
});

// 表格列配置
const columns = ref([])

const changeFreeDurationMode = (data) => {
  const value = data.target.value;
  if (value == "1") {
    freeDuration.value = "免费时长(分钟)";
  } else if (value == "2") {
    freeDuration.value = "免费时长(秒)";
  }
}

const changeTimeDivisionCharging = (data) => {
  const value = data.target.value;
  if (value == "2") {
    field.value = "ebikeSysRcostsetTimePeriodDtos";
    if (form.value['ebikeSysRcostsetTimePeriodDtos'] == null) {
      form.value['ebikeSysRcostsetTimePeriodDtos'] = [];
    }
    form.value.ebikeSysRcostsetWeekDtos = [];
    deteilShow.value = true;
    warmReminder.value = "温馨提示：当天结束的阶段为23:59:59，没有设置的话，默认配置为上面的字段。";
    columns.value = [
      {
        title: '阶段',
        key: 'phase',
        width: 70,
        align: 'center',
        dataIndex: 'phase'
      },
      {
        title: '起始时间',
        key: 'startupTime',
        width: 130,
        align: 'center',
        dataIndex: 'startupTime',
        type: 'time'
      },
      {
        title: '结束时间',
        key: 'endTime',
        width: 130,
        align: 'center',
        dataIndex: 'endTime',
        type: 'time'
      },
      {
        title: '起步费用(元)',
        key: 'startupCost',
        width: 120,
        align: 'center',
        dataIndex: 'startupCost',
        type: 'input'
      },
      {
        title: '起步时长(分)',
        key: 'startupDuration',
        width: 120,
        align: 'center',
        dataIndex: 'startupDuration',
        type: 'input'
      },
      {
        title: '时长费用(元)',
        key: 'durationCost',
        width: 120,
        align: 'center',
        dataIndex: 'durationCost',
        type: 'input'
      },
      {
        title: '时长(分)',
        key: 'duration',
        width: 100,
        align: 'center',
        dataIndex: 'duration',
        type: 'input'
      },
      {
        title: '操作',
        key: 'action',
        width: 80,
        align: 'center',
        fixed: 'right',
      }
    ]
  } else if (value == "3") {
    field.value = "ebikeSysRcostsetWeekDtos";
    if (form.value['ebikeSysRcostsetWeekDtos'] == null) {
      form.value['ebikeSysRcostsetWeekDtos'] = [];
    }
    form.value.ebikeSysRcostsetTimePeriodDtos = [];
    deteilShow.value = true;
    warmReminder.value = "温馨提示：周的日期支持多选，比如可以选择周一、周二、周三为1种计费方式，没有选择的按默认选择方式来。";
    columns.value = [
      {
        title: '名称',
        key: 'configName',
        width: 100,
        align: 'center',
        dataIndex: 'configName',
        type: 'input'
      },
      {
        title: '周',
        key: 'week',
        width: 170,
        align: 'center',
        dataIndex: 'week',
        type: 'select'
      },
      {
        title: '起步费用(元)',
        key: 'startupCost',
        width: 50,
        align: 'center',
        dataIndex: 'startupCost',
        type: 'input'
      },
      {
        title: '起步时长(分)',
        key: 'startupDuration',
        width: 120,
        align: 'center',
        dataIndex: 'startupDuration',
        type: 'input'
      },
      {
        title: '时长费用(元)',
        key: 'durationCost',
        width: 120,
        align: 'center',
        dataIndex: 'durationCost',
        type: 'input'
      },
      {
        title: '时长(分)',
        key: 'duration',
        width: 100,
        align: 'center',
        dataIndex: 'duration',
        type: 'input'
      },
      {
        title: '操作',
        key: 'action',
        width: 80,
        align: 'center',
        fixed: 'right',
      }
    ]
  } else {
    field.value = "";
    deteilShow.value = false;
    warmReminder.value = "";
    columns.value = []
    form.value.ebikeSysRcostsetTimePeriodDtos = [];
    form.value.ebikeSysRcostsetWeekDtos = [];
  }
}

const openForm = (params = {}) => {
  deteilShow.value = false;
  if (params['regionId']) {
    form.value.regionId = params['regionId']
    spinning.value = true;
    callOperate("/ebikesysrcostset/getRegionFeeConfigById?regionId="
      + params['regionId'], {}, "get").then(res => {
        spinning.value = false;
        if (res.code == 200) {
          if (res.data) {
            isAdd.value = false;
            form.value = res.data;
            if (res.data.timeDivisionCharging == '2') {
              const item = res.data.ebikeSysRcostsetTimePeriodDtos;
              if (item.length > 0) {
                item.forEach(t => {
                  t['startupTime'] = dayjs(t['startupTime'], 'HH:mm:ss');
                  t['endTime'] = dayjs(t['endTime'], 'HH:mm:ss');
                })
              }
              form.value.ebikeSysRcostsetTimePeriodDtos = item;
              field.value = "ebikeSysRcostsetTimePeriodDtos";
              deteilShow.value = true;
              warmReminder.value = "温馨提示：当天结束的阶段为23:59:59，没有设置的话，默认配置为上面的字段。";
              columns.value = [
                {
                  title: '阶段',
                  key: 'phase',
                  width: 70,
                  align: 'center',
                  dataIndex: 'phase'
                },
                {
                  title: '起始时间',
                  key: 'startupTime',
                  width: 130,
                  align: 'center',
                  dataIndex: 'startupTime',
                  type: 'time'
                },
                {
                  title: '结束时间',
                  key: 'endTime',
                  width: 130,
                  align: 'center',
                  dataIndex: 'endTime',
                  type: 'time'
                },
                {
                  title: '起步费用(元)',
                  key: 'startupCost',
                  width: 120,
                  align: 'center',
                  dataIndex: 'startupCost',
                  type: 'input'
                },
                {
                  title: '起步时长(分)',
                  key: 'startupDuration',
                  width: 120,
                  align: 'center',
                  dataIndex: 'startupDuration',
                  type: 'input'
                },
                {
                  title: '时长费用(元)',
                  key: 'durationCost',
                  width: 120,
                  align: 'center',
                  dataIndex: 'durationCost',
                  type: 'input'
                },
                {
                  title: '时长(分)',
                  key: 'duration',
                  width: 100,
                  align: 'center',
                  dataIndex: 'duration',
                  type: 'input'
                },
                {
                  title: '操作',
                  key: 'action',
                  width: 80,
                  align: 'center',
                  fixed: 'right',
                }
              ]
            } else if (res.data.timeDivisionCharging == '3') {
              field.value = "ebikeSysRcostsetWeekDtos";
              deteilShow.value = true;
              warmReminder.value = "温馨提示：周的日期支持多选，比如可以选择周一、周二、周三为1种计费方式，没有选择的按默认选择方式来。";
              columns.value = [
                {
                  title: '名称',
                  key: 'configName',
                  width: 100,
                  align: 'center',
                  dataIndex: 'configName',
                  type: 'input'
                },
                {
                  title: '周',
                  key: 'week',
                  width: 170,
                  align: 'center',
                  dataIndex: 'week',
                  type: 'select'
                },
                {
                  title: '起步费用(元)',
                  key: 'startupCost',
                  width: 120,
                  align: 'center',
                  dataIndex: 'startupCost',
                  type: 'input'
                },
                {
                  title: '起步时长(分)',
                  key: 'startupDuration',
                  width: 120,
                  align: 'center',
                  dataIndex: 'startupDuration',
                  type: 'input'
                },
                {
                  title: '时长费用(元)',
                  key: 'durationCost',
                  width: 120,
                  align: 'center',
                  dataIndex: 'durationCost',
                  type: 'input'
                },
                {
                  title: '时长(分)',
                  key: 'duration',
                  width: 100,
                  align: 'center',
                  dataIndex: 'duration',
                  type: 'input'
                },
                {
                  title: '操作',
                  key: 'action',
                  width: 80,
                  align: 'center',
                  fixed: 'right',
                }
              ]
            } else {
              field.value = "";
            }
          } else {
            formRef.value.resetFields()
          }
        } else {
          message.error(res.message);
        }
      })
  }
};

const addRecord = () => {
  const timeDivisionCharging = form.value.timeDivisionCharging;
  let item = {};
  let timeSegmentDetail = field.value
  if (timeDivisionCharging == '2') {
    item = {
      key: getGUID(),
      phase: "",
      startupTime: dayjs("00:00:00", 'HH:mm:ss'),
      endTime: dayjs("23:59:59", 'HH:mm:ss'),
      startupCost: "",
      startupDuration: "",
      durationCost: "",
      duration: ""
    };
  } else if (timeDivisionCharging == '3') {
    item = {
      key: getGUID(),
      configName: "",
      week: [],
      startupCost: "",
      startupDuration: "",
      durationCost: "",
      duration: "",
    };
  }
  form.value[timeSegmentDetail].push(item)
}

const deleteRecord = (record) => {
  const key = record['key'];
  let timeSegmentDetail = field.value
  let item = _.clone(form.value[timeSegmentDetail]);
  remove(key, "key", item)
  form.value[timeSegmentDetail] = item;
}

const remove = (val, filed, array) => {
  const index = array.findIndex(obj => obj[filed] === val);
  if (index > -1) {
    array.splice(index, 1);
  }
}

const formSave = () => {
  formRef.value.validate().then(() => {
    tipContent.value = "保存中..."
    spinning.value = true;
    let url = "regionFeeConfigAdds";
    if (!isAdd.value) {
      url = "updateRegionFeeConfig"
    }
    const param = _.cloneDeep(form.value)
    if (param['ebikeSysRcostsetTimePeriodDtos'] && param['ebikeSysRcostsetTimePeriodDtos'].length > 0) {
      param['ebikeSysRcostsetTimePeriodDtos'].forEach(item => {
        item['startupTime'] = item['startupTime'].format('HH:mm:ss');
        item['endTime'] = item['endTime'].format('HH:mm:ss');
      })
    }
    callOperate("/ebikesysrcostset/" + url, param).then(res => {
      spinning.value = false;
      if (props.onCallBack) {
        res.data = param;
        props.onCallBack(res);
        formRef.value.resetFields()
      }
    })
  }).catch(error => {
    console.log('error', error);
  });
};

defineExpose({ openForm, formSave });
</script>