<template>
  <div class="p-2">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="50%" :draggable="draggable">
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备机号" prop="termNo">
              <el-input v-model="formData.termNo" type="number" placeholder="请输入设备机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="termName">
              <el-input v-model="formData.termName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- :default-checked-keys="checkedKeys"
                :default-expanded-keys="expandKeys" -->
            <el-form-item label="所属餐厅" prop="roomId">
              <el-tree-select
                v-model="formData.roomId"
                :data="ptAreaOptions"
                :props="{ value: 'areaId', label: 'areaName', children: 'children' }"
                value-key="areaId"
                placeholder="请选择餐厅"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算账户" prop="accountId">
              <el-select v-model="formData.accountId" filterable placeholder="请选择结算账户">
                <el-option
                  v-for="item in accountOptions"
                  :key="item.accountId"
                  :label="item.accountName"
                  :value="item.accountId"
                  :disabled="false"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="termType">
              <el-select v-model="formData.termType" placeholder="请选择设备类型">
                <el-option v-for="dict in XF_TermType" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扣费类型" prop="consumeType">
              <el-select v-model="formData.consumeType" placeholder="请选择扣费类型">
                <el-option v-for="dict in XF_ConsumeType" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备IP" prop="termIp">
              <el-input v-model="formData.termIp" placeholder="请输入设备IP" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备端口" prop="commPort">
              <el-input v-model="formData.commPort" placeholder="请输入设备通讯端口" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器IP" prop="serverIp">
              <el-input v-model="formData.serverIp" placeholder="请输入服务器IP" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器端口" prop="serverPort">
              <el-input v-model="formData.serverPort" placeholder="请输入服务器端口" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否自动下载参数" prop="autoDown">
              <el-checkbox v-model="formData.autoDown" true-value="1" false-value="0" label="启用自动下载参数" border />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="formLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="XfTermForm" lang="ts">
import { listPtAccount } from '@/api/basics/merchant/ptAccount';
import { PtAccountVO } from '@/api/basics/merchant/ptAccount/types';
import { listPtArea } from '@/api/basics/room/ptArea';
import { PtAreaOption, PtAreaVO } from '@/api/basics/room/ptArea/types';
import { queryRoom2AreaList } from '@/api/basics/room/ptRoom';
import * as XfTermApi from '@/api/consumption/xfTerm';
import { XfTermForm } from '@/api/consumption/xfTerm/types';
import { useI18n } from 'vue-i18n';

defineOptions({ name: 'XfTermForm' });

// 接收父组件传入属性
const props = defineProps({
  ptAreaOptions: {
    type: Array<PtAreaOption>,
    default: []
  }
});

const expandKeys = ref([]);
const checkedKeys = ref<number[]>([]);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 国际化
const { t } = useI18n();
const accountOptions = ref<PtAccountVO[]>([]);
// const ptAreaOptions = ref<PtAreaOption[]>([]);

/** 数据字典 */
const { YYXT, XF_ConsumeType, XF_WorkMode, XF_TermType } = toRefs<any>(proxy?.useDict('YYXT', 'XF_ConsumeType', 'XF_WorkMode', 'XF_TermType'));
// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 窗体是否可以拖动
const draggable = ref(true);
// 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formLoading = ref(false);
// 表单的类型：create - 新增；update - 修改
const formType = ref('');
// 表单引用
const formRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<XfTermForm>({
  termId: undefined,
  termNo: undefined,
  termName: '',
  roomId: undefined,
  accountId: undefined,
  termType: '',
  qrCode: '',
  stationId: undefined,
  consumeType: '',
  autoDown: '1',
  useType: '',
  cardType: undefined,
  termIp: '',
  termMac: '',
  commPort: undefined,
  mask: '',
  serverIp: '',
  serverPort: undefined,
  gatewayIp: '',
  beatInterval: undefined,
  timeout: undefined,
  offlineTime: undefined,
  advParam: '',
  posParam: '',
  rateParam: '',
  workMode: '',
  openMode: '',
  maxCardMoney: undefined,
  constantValue: undefined,
  rationZero: undefined,
  rationOne: undefined,
  rationTwo: undefined,
  rationThree: undefined,
  rationFour: undefined,
  rationFive: undefined,
  rationSix: undefined,
  rationSeven: undefined,
  rationEight: undefined,
  rationNine: undefined,
  dayCount: undefined,
  dayMoney: undefined,
  mealCount: undefined,
  singleMoney: undefined,
  breakfastMoney: undefined,
  lunchMoney: undefined,
  supperMoney: undefined,
  nightMoney: undefined,
  breakfastBegin: undefined,
  breakfastEnd: undefined,
  lunchBegin: undefined,
  lunchEnd: undefined,
  supperBegin: undefined,
  supperEnd: undefined,
  nightBegin: undefined,
  nightEnd: undefined,
  swipeInterval: undefined,
  termValidity: '',
  recordId: undefined,
  uploadTime: undefined,
  blackDownTime: undefined,
  lastCheck: undefined,
  rebootTime: '',
  remark: ''
});
// 表单校验规则
const formRules = reactive({
  termId: [{ required: true, message: '设备Id,主键不能为空', trigger: 'blur' }],
  roomId: [{ required: true, message: '所属餐厅不能为空', trigger: 'blur' }],
  termNo: [{ required: true, message: '设备机号不能为空', trigger: 'blur' }],
  termName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  accountId: [{ required: true, message: '结算账户不能为空', trigger: 'blur' }],
  termType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
  consumeType: [{ required: true, message: '扣费类型不能为空', trigger: 'change' }],
  termIp: [{ required: true, message: '设备IP不能为空', trigger: 'blur' }],
  commPort: [{ required: true, message: '设备通讯端口不能为空', trigger: 'blur' }],
  serverIp: [{ required: true, message: '服务器IP不能为空', trigger: 'blur' }],
  serverPort: [{ required: true, message: '服务器端口不能为空', trigger: 'blur' }]
  /* workMode: [{ required: true, message: '消费工作模式,见XF_WorkMode字典类别不能为空', trigger: 'change' }],
  openMode: [{ required: true, message: '开机模式,0-不需要营业员开机,1-需要营业员开机不能为空', trigger: 'change' }],
  maxCardMoney: [{ required: true, message: '卡上最大金额不能为空', trigger: 'blur' }] */
});
/** 当前组件方法 */
/** 窗体打开事件 */
const open = async (type: string, id?: number) => {
  dialog.visible = true;
  dialog.title = t('action.' + type);
  formType.value = type;
  resetForm();
  expandKeys.value = [];
  /* if (props.ptAreaOptions.length > 0) {
    expandKeys.value.push(props.ptAreaOptions[0].areaId);
  } */
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      const res = await XfTermApi.getXfTerm(id);
      Object.assign(formData.value, res.data);
      // checkedKeys.value = [formData.value.roomId as number];
      expandKeys.value.push(formData.value.roomId as number);
    } finally {
      formLoading.value = false;
    }
  }
};
/** 表单重置 */
const resetForm = () => {
  formData.value = {
    termId: undefined,
    termNo: undefined,
    termName: '',
    roomId: undefined,
    accountId: undefined,
    termType: '',
    qrCode: '',
    stationId: undefined,
    consumeType: '',
    autoDown: '1',
    useType: '',
    cardType: undefined,
    termIp: '',
    termMac: '',
    commPort: undefined,
    mask: '',
    serverIp: '',
    serverPort: undefined,
    gatewayIp: '',
    beatInterval: undefined,
    timeout: undefined,
    offlineTime: undefined,
    advParam: '',
    posParam: '',
    rateParam: '',
    workMode: '',
    openMode: '',
    maxCardMoney: undefined,
    constantValue: undefined,
    rationZero: undefined,
    rationOne: undefined,
    rationTwo: undefined,
    rationThree: undefined,
    rationFour: undefined,
    rationFive: undefined,
    rationSix: undefined,
    rationSeven: undefined,
    rationEight: undefined,
    rationNine: undefined,
    dayCount: undefined,
    dayMoney: undefined,
    mealCount: undefined,
    singleMoney: undefined,
    breakfastMoney: undefined,
    lunchMoney: undefined,
    supperMoney: undefined,
    nightMoney: undefined,
    breakfastBegin: undefined,
    breakfastEnd: undefined,
    lunchBegin: undefined,
    lunchEnd: undefined,
    supperBegin: undefined,
    supperEnd: undefined,
    nightBegin: undefined,
    nightEnd: undefined,
    swipeInterval: undefined,
    termValidity: '',
    recordId: undefined,
    uploadTime: undefined,
    blackDownTime: undefined,
    lastCheck: undefined,
    rebootTime: '',
    remark: ''
  };
  formRef.value?.resetFields();
};
// 传回给父组件的属性与方法
// 提供 open 方法，用于打开弹窗
defineExpose({ open });
/** 触发父组件的事件 */
/** 定义 success 事件，用于操作成功后的回调 */
const emit = defineEmits(['success']);
/** 提交按钮 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return;
  const valid = await formRef.value?.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as XfTermForm;
    if (formType.value === 'create') {
      await XfTermApi.addXfTerm(data);
      proxy?.$modal.msgSuccess('新增成功');
    } else {
      await XfTermApi.updateXfTerm(data);
      proxy?.$modal.msgSuccess('修改成功');
    }
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

//查询账号信息
const getListAccount = () => {
  listPtAccount().then((res) => {
    accountOptions.value = res.rows;
  });
};

/** 初始化 */
onMounted(() => {
  getListAccount();
});
</script>
