<template>
  <a-spin
    :spinning="spinning"
    :tip="tipContent"
  >
    <a-divider orientation="left">开关配置</a-divider>
    <SwitchConfigForm ref="switchForm"></SwitchConfigForm>

    <a-divider orientation="left">运营配置</a-divider>
    <OperateConfigForm ref="operateForm"></OperateConfigForm>

    <a-divider orientation="left">用车配置</a-divider>
    <UseCarConfigForm ref="useCarForm"></UseCarConfigForm>

    <a-divider orientation="left">锁车配置</a-divider>
    <LockCarConfigForm ref="lockCarForm"></LockCarConfigForm>

    <a-divider orientation="left">还车配置</a-divider>
    <ReturnCarConfigForm ref="returnCarForm"></ReturnCarConfigForm>

    <a-divider orientation="left">客服配置</a-divider>
    <CustomerServiceConfigForm ref="customerServiceForm"></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 _ 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';
import dayjs from 'dayjs';


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

const switchForm = ref(null);
const operateForm = ref(null);
const useCarForm = ref(null);
const lockCarForm = ref(null);
const returnCarForm = ref(null);
const customerServiceForm = ref(null);
const isAdd = ref(true);
const spinning = ref(false);
const tipContent = ref("加载中...");
const operationRegionId = ref(null);

const openForm = (params = {}) => {
  isAdd.value = true;
  const forms = [switchForm, operateForm, useCarForm, lockCarForm, returnCarForm, customerServiceForm];
  if (params['operationRegionId']) {
    operationRegionId.value = params['operationRegionId'];
    spinning.value = true;
    callOperate("/ebikeSysRoperateset/getRegionConfigById?operationRegionId="
      + params['operationRegionId'], {}, "get").then(res => {
        spinning.value = false;
        if (res.code == 200) {
          if (res.data) {
            isAdd.value = false;
            forms.map(form => {
              const data = form.value.getFormData();
              if (data['tableName'] == "ebikeSysLinktelDto") {
                const ebikeSysLinktelDtos = _.cloneDeep(res.data['ebikeSysLinktelDtos']);
                let customerServiceConfig = [];
                ebikeSysLinktelDtos.map(item => {
                  customerServiceConfig.push({
                    telnum: item['telnum'],
                    workTime: [dayjs(item['worktimeStart'], 'HH:mm:ss'), dayjs(item['worktimeEnd'], 'HH:mm:ss')]
                  })
                })
                let formData = {
                  onlineService: res.data['ebikeSysRoperatesetDto']['onlineService'],
                  customerServiceConfig: customerServiceConfig
                }
                customerServiceForm.value.loadFormData(formData)
              } else {
                Object.keys(res.data).forEach((key) => {
                  if (key == data['tableName']) {
                    form.value.loadFormData(_.cloneDeep(res.data[key]));
                  }
                })
              }
            })
          } else {
            forms.map(form => {
              form.value.loadFormData();
            })
          }
        } else {
          message.error(res.message);
        }
      })
  }
};

const formSave = (onCallBack) => {
  const forms = [switchForm, operateForm, useCarForm, lockCarForm, returnCarForm, customerServiceForm];
  let params = {};
  // 创建一个数组，保存所有表单的校验 Promise
  const validationPromises = forms.map(form => {
    if (form.value) {
      return form.value.validateForm().then(res => {
        const tableName = res['tableName'];
        if (tableName == "ebikeSysLinktelDto") {
          params['ebikeSysRoperatesetDto'] = { ...params['ebikeSysRoperatesetDto'], onlineService: res['onlineService'] };
          params[tableName] = res['customerServiceConfig'];
          params[tableName].map(item => {
            item['operationRegionId'] = operationRegionId.value;
          })
        } else if (tableName == "ebikeSysRoperatesetDto") {
          delete res['tableName'];
          params[tableName] = { ...params['ebikeSysRoperatesetDto'], ...res };
          if (params[tableName]['operateTime']) {
            params[tableName]['operateTime'].map(item => {
              item['operationRegionId'] = operationRegionId.value;
            })
          }
          params[tableName]['operationRegionId'] = operationRegionId.value;
        } else {
          delete res['tableName'];
          params[tableName] = res;
          params[tableName]['operationRegionId'] = operationRegionId.value;
        }
      }).catch((e) => {
        return Promise.reject(e);
      });
    }
  });
  // 使用 Promise.all 等待所有的表单校验完成
  Promise.all(validationPromises).then(() => {
    tipContent.value = "保存中..."
    spinning.value = true;
    let url = "save";
    if (!isAdd.value) {
      url = "update"
    }
    if (params['ebikeSysRoperatesetDto']['rechargeRule']) {
      params['ebikeSysRoperatesetDto']['rechargeRule'] = params['ebikeSysRoperatesetDto']['rechargeRule'].map(item => item.value);
    }
    isAdd.value = false;
    callOperate("/ebikeSysRoperateset/" + url, params).then(res => {
      spinning.value = false;
      if (res.code == 200) {
        message.success(res.message)
        if (onCallBack) {
          res.data = params;
          onCallBack(res);
        }
      } else {
        message.error(res.message)
      }
    })
  }).catch(error => {
    console.log(error);
  });
};

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