<template>
  <!-- 远程做糖 -->
  <div class="sugarPage flex-col">
    <s-header :name="$t('device.remoteProduction')" :noback="false"></s-header>
    <div class="box1 flex-col">
      <div class="block2 flex-row justify-between">
        <div class="block3 flex-col"></div>
        <span class="info2">{{ $t('device.equipmentName') }}：{{ deviceDetal ? deviceDetal.name : '' }}</span>
      </div>
      <div v-if="machineType === null || machineType === '0'">
        <van-field v-model="fieldValue" is-link readonly :label="$t('device.clickToSelectPattern')"
          :placeholder="$t('device.pleaseSelectAPattern')" @click="show = true" />
        <van-popup v-model:show="show" round position="bottom">
          <van-cascader v-model="cascaderValue" :title="$t('device.pleaseSelectAPattern')" :options="options"
            @close="show = false" @finish="onFinish">
            <template #option="{ option }">
              <div class="cascader-item">
                <van-image :src="option.imgUrl" width="55px" height="55px"></van-image>
                <div class="cascader-label">{{ option.text }}</div>
              </div>
            </template>
          </van-cascader>
        </van-popup>
        <div class="textRow o-pr-20">
          <span @click="pushToDaySugarList">{{ $t('device.todaysSugarList') }}>></span>
        </div>
        <div v-if="!doSugartData" class="block5 flex-col" @click="submitDoSugar"><span class="txt3">{{
      $t('device.submitToMakeSugar') }}</span></div>
        <van-button v-if="doSugartData" style="padding: 1em;" round type="primary" class="block5 flex-col"
          :disabled="doSugartType" @click="checkData()">{{ $t('device.viewResults') }}</van-button>
      </div>
      <div v-if="machineType === '1'">
        <van-field v-model="fieldValue" is-link readonly :label="$t('device.clickToSelectTaste')"
          :placeholder="$t('device.pleaseSelectTaste')" @click="show = true" />
        <van-popup v-model:show="show" round position="bottom">
          <van-cascader v-model="cascaderValue" :title="$t('device.pleaseSelectTaste')" :options="options"
            @close="show = false" @finish="onFinish">
            <template #option="{ option }">
              <div class="cascader-item">
                <van-image :src="option.imgUrl" width="55px" height="55px"></van-image>
                <div class="cascader-label">{{ option.text }}</div>
              </div>
            </template>
          </van-cascader>
        </van-popup>
        <div class="textRow o-pr-20">
          <span @click="pushToDaySugarList">{{ $t('device.todaysMakeList') }}>></span>
        </div>
        <div v-if="!doSugartData" class="block5 flex-col" @click="submitDoSugar"><span class="txt3">{{
      $t('device.submitToMakeSugar') }}</span></div>
        <van-button v-if="doSugartData" style="padding: 1em;" round type="primary" class="block5 flex-col"
          :disabled="doSugartType" @click="checkData()">{{ $t('device.viewResults') }}</van-button>
      </div>
      <div v-if="machineType === '2'">
        <van-collapse v-model="activeNames">
          <van-collapse-item :title="$t('device.jam')" name="1" size="large" title-style="color: #404d74;">
            <van-row class="goods">
              <van-col v-for="(item, index) in jamData" :key="index" class="goodsCon o-mlr-5 o-mb-20" span="11">
                <div class="l-flex-RC">
                  <van-image width="50" height="50" fit="contain" :src="showPopPhoto(item)" />
                  <span class="o-ml-10" style="color: #000;word-wrap: break-word; width: 50px;">{{ item.name }}</span>
                  <van-checkbox class="o-ml-10" shape="square" v-model="item.checked" />
                </div>
              </van-col>
            </van-row>
          </van-collapse-item>
          <van-collapse-item :title="$t('device.nuts​')" name="2" size="large" title-style="color: #404d74;">
            <van-row class="goods">
              <van-col v-for="(item, index) in crushData" :key="index" class="goodsCon o-mlr-5 o-mb-20" span="11">
                <div class="l-flex-RC">
                  <van-image width="50" height="50" fit="contain" :src="showPopPhoto(item)" />
                  <span class="o-ml-10" style="color: #000;word-wrap: break-word; width: 50px;">{{ item.name }}</span>
                  <van-checkbox class="o-ml-10" shape="square" v-model="item.checked" />
                </div>
              </van-col>
            </van-row>
          </van-collapse-item>
        </van-collapse>
        <br>
        <div class="textRow o-pr-20">
          <span @click="pushToDaySugarList">{{ $t('device.todaysMakeList') }}>></span>
        </div>
        <div v-if="!doSugartData" class="block5 flex-col" @click="submitDoSugar"><span class="txt3">{{
      $t('device.submitToMakeSugar') }}</span></div>
        <van-button v-if="doSugartData" style="padding: 1em;" round type="primary" class="block5 flex-col"
          :disabled="doSugartType" @click="checkData()">{{ $t('device.viewResults') }}</van-button>
      </div>
    </div>
  </div>
</template>
<script>
import { onMounted, ref } from 'vue';
import sHeader from "@/components/SimpleHeader";
import { useRoute, useRouter } from 'vue-router';
import {
  getDeviceDetal, selectProducts,
  remoteProduction,
  selectSugarStatus
} from '@/service/device'
import { showConfirmDialog, showFailToast, showSuccessToast, showToast } from 'vant';
import { useI18n } from 'vue-i18n';
import { styleUrl } from "../../common/js/utils";

export default {
  setup() {
    const { t } = useI18n();
    const route = useRoute();
    const router = useRouter();
    const deviceId = route.query.deviceId;
    const machineType = route.query.machineType;
    const deviceDetal = ref(null);
    const show = ref(false);
    const fieldValue = ref('');
    const cascaderValue = ref('');
    const options = ref([]);
    const activeNames = ref(['1', '2']);
    const productNo = ref('');

    // 果酱数据
    const iceName = ref();
    const jamData = ref([]);
    const crushData = ref([]);

    // 商品图片
    const showPopPhoto = (row) => {
      let imgId = row.no;
      if (imgId) {
        return require(`../../assets/order/spunSugar/goods/${imgId}.png`);
      }
      return imgId;
    };
    const onFinish = ({ selectedOptions }) => {
      console.log('onFinish', selectedOptions);
      show.value = false;
      fieldValue.value = selectedOptions[0].text;
      productNo.value = selectedOptions[0].value;
    }
    const doSugartData = ref(null);
    const doSugartType = ref(true);

    // 初始化页面获取列表
    onMounted(async () => {
      styleUrl('doSugar')
      getDeviceDetalFun();
    });

    const showSugarPhoto = (no) => {
      return require(`../../assets/order/spunSugar/goods/${no}.png`);
    };

    // 获取设备列表数据
    const getDeviceDetalFun = async () => {
      const { data } = await getDeviceDetal({ id: deviceId });
      if (data.code === '00000') {
        deviceDetal.value = data.data;
        getProduct();
      } else { showFailToast(data.message); }
    }
    // 获取花形下拉列表
    const getProduct = async () => {
      const { data } = await selectProducts({ equipmentId: deviceId });
      if (data.code) {
        if (machineType != '2') {
          options.value = data.data.map(item => {
            return {
              text: item.productName,
              value: item.no,
              imgUrl: showSugarPhoto(item.no),
            };
          })
        } else {
          data.data.forEach(item => {
            if (item.no.includes('J01')) {
              // 果酱1
              jamData.value.push({
                name: item.productName,
                no: item.no,
                value: 1,
                checked: false
              });
            } else if (item.no.includes('J02')) {
              // 果酱2
              jamData.value.push({
                name: item.productName,
                no: item.no,
                value: 2,
                checked: false
              });
            } else if (item.no.includes('J03')) {
              // 果酱3
              jamData.value.push({
                name: item.productName,
                no: item.no,
                value: 3,
                checked: false
              });
            } else if (item.no.includes('C01')) {
              // 果碎1
              crushData.value.push({
                name: item.productName,
                no: item.no,
                value: 1,
                checked: false
              });
            } else if (item.no.includes('C02')) {
              // 果碎2
              crushData.value.push({
                name: item.productName,
                no: item.no,
                value: 2,
                checked: false
              });
            } else if (item.no.includes('I01')) {
              // 雪糕
              iceName.value = item.productName;
            }
          })
        }
      } else { showFailToast(data.message); }
    }
    const submitDoSugar = async () => {
      const makeCodes = ref([1, 0, 0]);
      doSugartData.value = null;
      doSugartType.value = true;

      if (machineType == '2') {
        fieldValue.value = '';
        let jamCount = 0;
        let crushCount = 0;
        // 如果是冰淇淋机器
        jamData.value.forEach(item => {
          if (item.checked) {
            fieldValue.value += item.name + ',';
            makeCodes.value[1] += item.value;
            jamCount++;
          }
        });
        crushData.value.forEach(item => {
          if (item.checked) {
            fieldValue.value += item.name + ',';
            makeCodes.value[2] += item.value;
            crushCount++;
          }
        });
        if (jamCount > 1) {
          makeCodes.value[1] += 1;
        }
        if (crushCount > 1) {
          makeCodes.value[2] += 1;
        }
        if (fieldValue.value === '') {
          fieldValue.value = iceName.value;
        } else {
          fieldValue.value = fieldValue.value.substring(0, fieldValue.value.length - 1);
          fieldValue.value = iceName.value + "(" + fieldValue.value + ")";
        }
      }
      if (fieldValue.value === '') { showFailToast(t('device.pleaseSelectAPattern')); return; }
      showConfirmDialog({
        title: t('user.tips'),
        message: t('device.confirmMake')+ fieldValue.value +'?',
      }).then(async() => {
        const { data } = await remoteProduction({ 
          equipmentId: deviceId, 
          productName: fieldValue.value, 
          makeCodes: makeCodes.value.join(','),
          productNo: productNo.value
         });
        if (data.code == "00000") {
          doSugartData.value = data.data;
          setTimeout(() => {
            doSugartType.value = false;
          }, 5000);
        } else { showFailToast(data.message); }
      }).catch((error) => {
        console.error(error);
      })
    }
    const checkData = async () => {
      const { data } = await selectSugarStatus({ no: doSugartData.value.no });
      if (data.code) {
        if (data.data == '1') {
          showToast(t('device.receiveInstruction'));
        } else {
          showSuccessToast(data.message);
        }
        doSugartData.value = null;
        doSugartType.value = true;
      } else {
        if (data.data == '0') {
          showToast(t('device.notUploadData'));
        } else if (data.data == '2') {
          showToast(t('device.machineException'));
        } else if (data.data == '3') {
          showToast(t('device.netException'));
        } else {
          showToast(data.message);
        }
      }
    };

    const pushToDaySugarList = async () => {
      router.push({ path: 'toDaySugarList', query: { deviceId: deviceId, clientId: deviceDetal.value.clientId } })
    }

    return {
      deviceDetal,
      show,
      fieldValue,
      cascaderValue,
      options,
      onFinish,
      submitDoSugar,
      doSugartData,
      doSugartType,
      checkData,
      pushToDaySugarList,
      showSugarPhoto,
      machineType,
      activeNames,
      jamData,
      crushData,
      showPopPhoto
    };
  },
  components: { sHeader },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common";
</style>
