<template>
  <div class="showGoodsIdx">
    <s-header :name="$t('device.diyFlower')" :noback="false"></s-header>
    <div class="headerCon kBordBott o-plr-10 o-ptb-16 l-flex-RC">
      <div class="line o-mr-6"></div>
      <div>
        <span class="c-color c-text-14">{{ $t('device.showGoodsPage.equipmentName') }}：</span>
        <span class="c-text-color c-text-14">{{ equipmentName }}</span>
      </div>
    </div>
  </div>
  <van-cell center :title="checked ? $t('DIYFlower.openStatus') : $t('DIYFlower.closeStatus')" size="large"
    title-style="color: #404d74;">
    <template #right-icon>
      <van-switch :model-value="checked" @update:model-value="updateStatus" size="24" />
    </template>
  </van-cell>
  <van-collapse v-if="checked" v-model="activeNames">
    <van-collapse-item :title="$t('DIYFlower.shape')" name="1" size="large" title-style="color: #404d74;">
      <van-row class="goods">
        <van-col v-for="(item, index) in shapeData" :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="showSugerPhoto(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="shapeStates[index]" @change="shapeChange(index)" />
          </div>
        </van-col>
      </van-row>
    </van-collapse-item>
    <van-collapse-item :title="$t('DIYFlower.sugar')" name="2" size="large" title-style="color: #404d74;">
      <van-row class="goods">
        <van-col v-for="(item, index) in sugarData" :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="showSugerPhoto(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="sugarStates[index]" @change="sugarChange(index)" />
          </div>
        </van-col>
      </van-row>
    </van-collapse-item>
  </van-collapse>
  <div class="l-flex-center" v-if="checked" style="margin: 16px">
    <van-button round block class="Btn" type="primary" native-type="submit" @click="updateShowGoods()">
      {{ $t('device.submitAndPushDeviceUpdates') }}
    </van-button>
  </div>
</template>

<script>
// 导入接口
import { selectDIYFlowers, updateDIYFlowerStatus, updateDIYProductShow } from '@/service/device/index';
import sHeader from "@/components/SimpleHeader";
import { ref, reactive } from "@vue/reactivity";
import { onMounted } from '@vue/runtime-core';
import { useRoute, useRouter } from 'vue-router';
import { Dialog, Toast } from 'vant';
import { useI18n } from "vue-i18n";
import { styleUrl } from '../../../common/js/utils';
export default {
  components: {
    sHeader
  },
  setup() {
    // 引入语言
    const { t } = useI18n();
    // 路由
    const route = useRoute();
    const router = useRouter();
    // 商品数据
    const shapeData = ref([]);
    const sugarData = ref([]);

    const switchStates = ref([]);
    const shapeStates = ref([]);
    const sugarStates = ref([]);

    // 设备名称
    const equipmentName = ref('');
    const checked = ref(false);
    // 刚进页面
    onMounted(() => {
      // 加载样式
      styleUrl('showGoods');
      const id = route.query.deviceId || "";
      const name = route.query.name || "";
      const diyFlowerStatus = route.query.diyFlowerStatus || "";

      if (diyFlowerStatus == "1") {
        checked.value = true;
        cofficentForm.equipmentId = id;
        getList();
      }
      if (id) {
        equipmentName.value = name;
      }

    });
    const showSugerPhoto = (row) => {
      let imgId = row.no;
      if (imgId) {
        return require(`../../../assets/device/diyFlowers/${imgId}.png`);
      }
      return imgId;
    };
    // 获取商品列表
    const getList = () => {
      const flower = route.query.flower || "";
      selectDIYFlowers({
        equipmentId: cofficentForm.equipmentId
      }).then(res => {
        console.log('res', res)
        const {
          data
        } = res.data;
        if (data) {
          if (data.length > 0) {
            // 是否修改状态
            data.forEach(item => {
              flowerNumber(item, flower);
              if (item.no.includes('T')) {
                sugarData.value.push(item);
                if (item.showType == null || item.showType == '0') {
                  sugarStates.value.push(false);
                } else {
                  sugarStates.value.push(true);
                }
              }
            })
          }
        }
      })
    }
    // 修改的价格
    const cofficentForm = reactive({
      equipmentId: '',
    });

    // 判断花型数目
    const flowerNumber = (item, number) => {
      var shape = null;
      if (number == '18') {
        shape = ['S01', 'S02', 'S03'];
      } else if (number == '22') {
        shape = ['S01', 'S02', 'S03', 'S04'];
      } else if (number == '26') {
        shape = ['S01', 'S02', 'S03', 'S04', 'S05'];
      } else if (number == '30') {
        shape = ['S01', 'S02', 'S03', 'S04', 'S05', 'S06'];
      } else {
        shape = ['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09'];
      }
      if (shape.includes(item.no)) {
        shapeData.value.push(item);
        if (item.showType == null || item.showType == '0') {
          shapeStates.value.push(false);
        } else {
          shapeStates.value.push(true);
        }
      }
    }

    // 更改状态
    const shapeChange = (index) => {
      if (shapeStates.value[index]) {
        shapeData.value[index].showType = 1;
      } else {
        shapeData.value[index].showType = 0;
      }
      console.log("形状", shapeData.value[index]);
    };
    const sugarChange = (index) => {
      if (sugarStates.value[index]) {
        sugarData.value[index].showType = 1;
      } else {
        sugarData.value[index].showType = 0;
      }
      console.log("糖", sugarData.value[index]);
    };

    const updateStatus = (newValue) => {
      const params = {
        equipmentId: cofficentForm.equipmentId,
        DIYFlowerStatus: newValue ? '1' : '0',
      };
      Dialog.confirm({
        title: t('DIYFlower.tips'),
        message: t('DIYFlower.content'),
      }).then(async () => {
        const { data } = await updateDIYFlowerStatus(params);
        if (data.code) {
          // checked.value = newValue;
          Toast(t('DIYFlower.successfully'));
          setTimeout(() => {
            router.go(-1);
          }, 1500);
        } else {
          Toast.fail(data.message);
        }
      }).catch((error) => {
        console.log(error);
        Toast.fail(t('device.unknownError'));
      });
    }

    // 点击提交
    const updateShowGoods = () => {
      Dialog.confirm({
        title: t('device.openRemind'),
        message: t('device.editCheck'),
      }).then(() => {
        var products = shapeData.value.concat(sugarData.value);
        var list = JSON.stringify(products);
        console.log(list);

        updateDIYProductShow({
          productList: list
        }).then((res) => {
          console.log(res.data.message);
          Dialog.alert({
            message: t('DIYFlower.successfully'),
          }).then(() => {
            //返回上一页
            router.go(-1);
          });
          // setTimeout(() => {
          //   getList();
          // }, 1000);
        }).catch((error) => {
          console.log(error);
          Toast.fail(t('device.unknownError'));
        });
      });
    };
    const activeNames = ref(['1', '2']);

    return {
      cofficentForm,
      shapeData,
      sugarData,
      equipmentName,
      updateShowGoods,
      switchStates,
      shapeStates,
      sugarStates,
      shapeChange,
      sugarChange,
      checked,
      showSugerPhoto,
      activeNames,
      updateStatus
    };
  },
};
</script>

<style lang="less" scoped></style>
