<template>
  <view class="container">
    <view class="form-panel">
      <uni-forms ref="ebikeInfoForm" :modelValue="ebikeInfo" labelWidth="100px">
        <uni-section title="车辆" type="line">
          <uni-forms-item
            label="车辆编号"
            required
            name="bikeCode"
            :rules="[{ required: true, errorMessage: '请扫描或输入车辆编号' }]"
          >
            <bikeCodeScan
              @scan-change="bikeCodeScanChange"
              :codeValue="ebikeInfo.bikeCode"
              ref="bikeCodeScanRef"
            />
          </uni-forms-item>
          <uni-forms-item
            label="车辆型号"
            required
            name="bikeModel"
            :rules="[{ required: true, errorMessage: '请输入车辆型号' }]"
          >
            <uni-easyinput
              v-model="ebikeInfo.bikeModel"
              placeholder="请输入车辆型号"
            />
          </uni-forms-item>
          <uni-forms-item label="车牌号" name="bikeNumber">
            <uni-easyinput
              v-model="ebikeInfo.bikeNumber"
              placeholder="请输入车牌号"
            />
          </uni-forms-item>
        </uni-section>
        <uni-section title="中控" type="line">
          <uni-forms-item
            label="中控IMEI"
            required
            :name="['ebikeEcuInfo', 'ecuCode']"
            :rules="[{ required: true, errorMessage: '请扫描或输入中控IMEI' }]"
          >
            <ecuCodeScan
              @scan-change="ecuCodeScanChange"
              :codeValue="ebikeInfo.ebikeEcuInfo.ecuCode"
              ref="ecuCodeScan_zk"
            />
          </uni-forms-item>
          <uni-forms-item
            label="中控SN"
            required
            :name="['ebikeEcuInfo', 'ecuSn']"
            :rules="[{ required: true, errorMessage: '请输入中控SN' }]"
          >
            <uni-easyinput
              v-model="ebikeInfo.ebikeEcuInfo.ecuSn"
              placeholder="请输入中控SN"
              @change="ecuSNModelChange"
            />
          </uni-forms-item>
          <uni-forms-item
            label="中控品牌"
            required
            :name="['ebikeEcuInfo', 'ecuModel']"
            :rules="[{ required: true, errorMessage: '请选择中控品牌' }]"
          >
            <uni-data-select
              v-model="ebikeInfo.ebikeEcuInfo.ecuModel"
              :localdata="ecuModelRange"
              @change="ecuModelChange"
              placeholder="请选择中控品牌"
            ></uni-data-select>
          </uni-forms-item>
        </uni-section>
        <uni-section title="电池" type="line">
          <uni-forms-item
            label="电池编号"
            required
            :name="['ebikeBatteryInfo', 'batteryCode']"
            :rules="[{ required: true, errorMessage: '请扫描或输入电池编号' }]"
          >
            <scanCode
              @scan-change="batteryCodeScanChange"
              :codeValue="ebikeInfo.ebikeBatteryInfo.batteryCode"
              ref="scanCode_dc"
            />
          </uni-forms-item>
        </uni-section>
        <uni-section title="头盔" type="line">
          <uni-forms-item
            label="头盔编号"
            :name="['ebikeHelmetInfo', 'helmetCode']"
          >
            <scanCode
              @scan-change="helmetCodeScanChange"
              :codeValue="ebikeInfo.ebikeHelmetInfo.helmetCode"
              ref="scanCode_tk"
            />
          </uni-forms-item>
        </uni-section>
      </uni-forms>
    </view>
  </view>
  <view class="nav-panel">
    <c-uni-goods-nav
      :fill="true"
      :options="[]"
      :buttonGroup="navButtonGroup"
      @buttonClick="navButtonClick"
    />
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import * as api from "@/utils/api.js";
import { showModelMessage } from "@/utils/tools";
const ebikeInfoForm = ref(null);
const bikeCodeScanRef = ref(null);
const ecuCodeScan_zk = ref(null);
const scanCode_dc = ref(null);
const scanCode_tk = ref(null);

const ebikeInfo = ref({
  bikeCode: "",
  bikeModel: "",
  bikeNumber: "",
  ebikeEcuInfo: {
    ecuCode: "",
    ecuSn: "",
    ecuModel: "",
  },
  ebikeBatteryInfo: {
    batteryCode: "",
  },
  ebikeHelmetInfo: {
    helmetCode: "",
  },
});

const ecuModelRange = [
  {
    value: "乐摇摇",
    text: "乐摇摇",
  },
  {
    value: "美团",
    text: "美团",
  },
];

const navButtonGroup = reactive([
  {
    text: "入库",
    backgroundColor: "#0078D4",
    color: "#fff",
    disable: false,
  },
]);

const navButtonClick = (e) => {
  const index = e.index;
  //navButtonGroup[index].disable = true;
  if (index == 0) {
    if (ebikeInfoForm.value) {
      // 确保表单元素已挂载
      ebikeInfoForm.value
        .validate()
        .then((res) => {
          handleSubmit();
        })
        .catch((err) => {
          //console.log('err', err);
        });
    } else {
      //console.error('Form element is not available'); // 调试信息，以防万一
    }
  }
};

const ecuSNModelChange = (value) => {
  console.log(value);
};

const ecuModelChange = (value) => {
  ebikeInfo.value.ebikeEcuInfo.ecuModel = value;
};

const handleSubmit = () => {
  const params = ebikeInfo.value;
  api
    .callEbikeInfo("saveEbikeInfo", params)
    .then((res) => {
      uni.showToast({
        title: "入库成功",
        icon: "success",
        duration: 5000,
        success: (res) => {
          setTimeout(function () {
            uni.navigateBack();
          }, 5000);
        },
      });
    })
    .catch((err) => {
      uni.showToast({
        title: "入库失败",
        icon: "error",
        duration: 5000,
      });
    });
};

let timer;
const bikeCodeScanChange = (data) => {
  // clearTimeout(timer);
  ebikeInfo.value.bikeCode = data;
  if (!data) return;
  // timer = setTimeout(function() {
  api
    .callEbikeInfo("getBikeINfoData?bikeCode=" + data)
    .then((res) => {
      if (res.code == 200 && res.data && res.data.bikeId) {
        showModelMessage("车辆信息已存在!");
        ebikeInfo.value.bikeCode = "";
        bikeCodeScanRef.value.onSetValue("");
      } else {
        api
          .callOperateApi(
            "ebikeBikeQrcode/checkBikeCodeExistence?bikeCode=" + data,
            {},
            "get"
          )
          .then((res) => {
            if (res.code == 200) {
              if (res.data > 0) {
                ebikeInfo.value.bikeCode = data;
              } else {
                ebikeInfo.value.bikeCode = "";
                bikeCodeScanRef.value.onSetValue("");
                showModelMessage("车辆编号二维码未生成,请重新扫码或输入!");
              }
            }
          });
      }
    })
    .catch((err) => {
      ebikeInfo.value.bikeCode = data;
    });
  // }, 1000);
};
const ecuCodeScanChange = (data) => {
  console.log(data);
  let code = data["sn"] || data["imei"];
  //   if (!data["sn"]) return;

  const params = {
    componentCode: code,
    componentType: "262711452730008", //中控
  };
  console.log(params);

  api
    .callOperateApi("ebikeComponent/validateComponentExistence", params)
    .then((res) => {
      if (res.code == 200) {
        if (res.data) {
          ebikeInfo.value.ebikeEcuInfo.ecuCode = data["imei"];
          ebikeInfo.value.ebikeEcuInfo.ecuSn = data["sn"];
        } else {
          ebikeInfo.value.ebikeEcuInfo.ecuCode = "";
          ebikeInfo.value.ebikeEcuInfo.ecuSn = "";
          ecuCodeScan_zk.value.onSetValue("");
          showModelMessage("中控不在仓库中,请重新扫码或输入!");
        }
      } else {
        ebikeInfo.value.ebikeEcuInfo.ecuCode = "";
        ebikeInfo.value.ebikeEcuInfo.ecuSn = "";
        ecuCodeScan_zk.value.onSetValue("");
        showModelMessage("操作失败！");
      }
    });
};

const batteryCodeScanChange = (data) => {
  if (!data) return;
  const params = {
    componentCode: data,
    componentType: "262711452730000", //电池
  };
  api
    .callOperateApi("ebikeComponent/validateComponentExistence", params)
    .then((res) => {
      if (res.code == 200) {
        if (res.data) {
          ebikeInfo.value.ebikeBatteryInfo.batteryCode = data;
        } else {
          ebikeInfo.value.ebikeBatteryInfo.batteryCode = "";
          scanCode_dc.value.onSetValue("");
          showModelMessage("电池不在仓库中,请重新扫码或输入!");
        }
      } else {
        scanCode_dc.value.onSetValue("");
        ebikeInfo.value.ebikeBatteryInfo.batteryCode = "";
        showModelMessage("操作失败！");
      }
    });
};

const helmetCodeScanChange = (data) => {
  if (!data) return;
  const params = {
    componentCode: data,
    componentType: "262711452730001", //头盔
  };
  api
    .callOperateApi("ebikeComponent/validateComponentExistence", params)
    .then((res) => {
      if (res.code == 200) {
        if (res.data > 0) {
          ebikeInfo.value.ebikeHelmetInfo.helmetCode = data;
        } else {
          ebikeInfo.value.ebikeHelmetInfo.helmetCode = "";
          scanCode_tk.value.onSetValue("");
          // bikeCodeScanRef.value.onSetValue("");
          showModelMessage("头盔不在仓库中,请重新扫码或输入!");
        }
      } else {
        scanCode_tk.value.onSetValue("");
        ebikeInfo.value.ebikeHelmetInfo.helmetCode = "";
        showModelMessage("操作失败！");
      }
    });
};
</script>

<style>
.container {
  padding: 15px;
  background-color: #fff;
}

/* 全局样式 */
/* 	.uni-forms .uni-forms-item__label {
	  width: 100px !important; 
	} */

.form-panel {
  padding-bottom: 55px;
}

.nav-panel {
  position: fixed;
  bottom: 0rpx;
  width: 100%;
  padding-bottom: 10px;
  z-index: 999;
  background-color: #fff;
}
</style>
