<template>
  <el-container>
    <el-main class="nopadding">
      <!-- <input class="input" id="inputsmq" ref="inputRef" type="password" /> -->
      <input class="input" id="inputsmq" ref="scannerInput" type="text" @input="handleScannerInput" @focus="onFocus" @blur="blurfun" />
      <div class="pos">
          <el-row>
            <el-col :span='9' class="pos_order" id="order_list">
              <el-tabs style="padding-left:10px;">
                  <el-tab-pane label="购物单">
                    

                    <div class="card" v-for="(item, index) in listdata" :key="index">
                      <div class="top">
                        <div class="shop_name">{{ item.title }}</div>
                      </div>
                      <div class="main">
                        <div class="card_wrap" v-for="(cc, inner) in item.content" :key="inner">
                          <div class="card_item" right-width="65">
                            <div class="card_item_wrap">
                              <div class="select_box" @click="goodsSelectedHandle(cc.goods_id, cc.goods_sku_id)">
                               
                              </div>
                              <div class="img_wrap">
                                <img :src="cc.goods.cover" mode="aspectFill" />
                              </div>
                              <div class="info">
                                <div class="it">
                                  <div class="goods_title">
                                    {{ cc.goods.title }}
                                  </div>

                                  <div class="deleteicon">
                                    <div  class="delete" @click="goodsDeleteHandle(cc.goods_id, cc.goods_sku_id)">删除</div>
                                  </div>

                                  <!-- @click="skuChangeHandle(cc)" -->
                                  <div class="sku" v-if="cc.sku" >
                                    <div class="text">{{ cc.sku.sku }}</div>
                                  </div>
                                </div>
                                <div class="ib">
                                  <div class="pricebox">
                                    <div class="price">
                                      <div class="price_icon">¥</div>
                                      <div class="price_main din">
                                        {{ cc.formatBig }}
                                        <text class="mini">{{ cc.formatMini }}</text>
                                      </div>
                                    </div>

                                    <div class="price jfprice">
                                      <div class="price_icon">积分:</div>
                                      <div class="price_main din">
                                        {{ cc.goods.integral }}
                                      </div>
                                    </div>

                                  </div>
                                  <div class="num">
                                      <el-input-number :data-gid="cc.goods_id" :data-sid="cc.goods_sku_id"
                                      :data-cid="cc.cart_id" :min="1" @change="(e)=>stepMinusHandle(e, cc)" size="small" v-model="cc.num"></el-input-number>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>


                    <div class="total">
                      <small>数量:</small>{{ totalCount }}<small>金额:</small>￥{{ totalMoney }}
                      <small>所需积分:</small>{{ totaljifen }}
                      
                    </div>
                    <div class="pos_btn">
                      <el-button size="large" type="primary" @click="focusfun" >监听扫码枪识别</el-button>
                      <el-button size="large" type="danger" @click="delAllGoods()">清空购物单</el-button>
                      <el-button size="large" type="success" @click="checkOut()">结算</el-button>
                    </div>
                  </el-tab-pane> 
              </el-tabs>
            </el-col>
            <el-col :span="15">
                <el-header>
                  <div class="left-panel">
                    <el-input v-model="search.keyword" placeholder="关键词" style="width:150px; margin-right: 10px;" clearable />
                    <sc-select-tree v-model="search.category_id" :apiObj="$API.goods.category.list" :props="{label: 'title', value: 'id'}" style="width: 240px; margin-right: 10px;" />
                    <el-select v-model="search.status" placeholder="状态" clearable style="width: 100px;">
                      <el-option v-for="item in [{value: 0, title: '下架'}, {value: 1, title: '上架'}]" :key="item.value" :label="item.title" :value="item.value" />
                    </el-select>
                    <el-button-group style="margin-left: 10px;">
                      <el-button type="primary" icon="el-icon-search" @click="upsearch">搜索</el-button>
                    </el-button-group>
                  </div>
                </el-header>
                
                <scTable tableName="member" ref="table" :apiObj="list.apiObj" :column="list.column" row-key="id" @selection-change="selectionChange" border stripe>
                  <el-table-column type="selection" width="50"></el-table-column>
                  <template #cover="scope">
                    <img :src="scope.row.cover" width="40" height="40" v-if="scope.row.cover" />
                  </template>
                  <template #status="scope">
                    <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">{{scope.row.status == 1 ? '上架' : '下架'}}</el-tag>
                  </template>
                  <el-table-column label="操作" fixed="right" align="center" width="140">
                    <template #default="scope">
                      <el-button-group>
                        <el-button type="primary" @click="addOrderList(scope.row, scope.$index)">添加</el-button>
                        
                      </el-button-group>
                    </template>
                  </el-table-column>
                </scTable>

              </el-col>
          </el-row>
        </div>

        <!-- 弹窗选择规则 -->
        <el-dialog
          v-model="dialogVisible"
          title="选择规格"
          width="500"
          :before-close="handleClose"
        >
          <div>
            <div class="sku_card" v-for="(item, outer) in childgoods.spec_list" :key="outer">
              <div class="sku_card_title">{{ item.name }}</div>
              <div class="sku_card_main">
                <div :class="{
                    sku_card_item: true,
                    sku_card_item_active: item.value[inner] === item.selected,
                  }" v-for="(cc, inner) in item.value" :key="inner" @click="skuTapHandle(item, outer, cc)">
                  {{ cc }}
                </div>
              </div>
            </div>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="addCartHandle()">
                确定
              </el-button>
            </div>
          </template>
        </el-dialog>


    </el-main>
  </el-container>
</template>
<script >

import { ElLoading, ElMessage } from "element-plus";
import { ElMessageBox } from 'element-plus'
export default {
  name: "ucenter.cashierhome",
  components: {},
  data() {
    return {
        childgoods:{spec_list:[]},
        dialogVisible:false,

        dialog: {search: false, import: false, print: false},
        list: {
          apiObj: this.$API.goods.lists.list,
          column: [
            {prop: 'id', label: 'ID', width: 80},
            {prop: 'goods_sn', label: '商品编号'},
            {prop: 'title', label: '商品名称'},
            {prop: 'cover', label: '封面图', width: 120},
            {prop: 'price', label: '售价', width: 120},
            {prop: 'original_price', label: '原价', width: 120},
            // {prop: 'status', label: '状态', width: 80},
          ],
        },
        selection: [],
        search: {},

        totalMoney: 0,
        totalCount: 0,


        loading:null,
        scannedCode: '', // 存储扫码后的结果  结果
        isTyping: false, // 用户是否正在手动输入
        typingTimeout: null, // 用于判断输入间隔的定时器



        // 原始数据 购物车
				odata: [],
				listdata: [],
				mirror: [],
				total: 0,
        totaljifen:0,//总共所需积分
				totalFormatBig: 0,
				totalFormatMini: ".00",
      
    };
  },
  mounted(){
    var orderHeight = document.body.clientHeight;
    document.getElementById("order_list").style.height = orderHeight + "px";

  },
  created: function() {
    this.getCartList();//获取购物清单
  },
  watch:{
    listdata:{
      handler(newValue) {
					let total = 0;
          let totalCount = 0;
          let totaljifen = 0;
					newValue.forEach((item) => {
						item.content.forEach((cc) => {
							
							total += Number(cc.readyPrice) * Number(cc.num);
							totalCount = totalCount + cc.num;

              totaljifen += Number(cc.ready_integral) * Number(cc.num)
						});
					});
					total = total.toFixed(2);
					const priceParts = total.split(".");
					const formatBig = priceParts[0];
					const formatMini = priceParts.length > 1 ? `.${priceParts[1]}` : ".00";
					this.totalMoney = total;
          this.totalCount = totalCount;
          this.totaljifen = totaljifen;//积分

					// this.totalFormatBig = formatBig;
					// this.totalFormatMini = formatMini;
				},
				deep: true,
    }
  },
  methods: {
    //---规格加入购物车-------------------------------------------------------------------------
    popCloseHandle() {
      this.$emit("close");
    },
    //规格提交
    addCartHandle() {
      this.dialogVisible = false;
      let skuId = this.childgoods.skuId;
      let number = this.childgoods.popNumber;
      // this.$emit("popAddCart", skuId, number);
      this.addCart("multiple", skuId, number);

      
    },
    //提交加入购物车
    addCart(type, skuId, number) {
      let that = this;
      let req = {};
      if (type === "single") {//没有规格
        req = {
          goods_sn:that.childgoods.goods_sn,//商品编号
          goods_id: that.childgoods.id,
          goods_sku_id: 0,
          num: 1,
          store_id: that.childgoods.store_id,
        };
      } else {//有规格
        req = {
          goods_sn:that.childgoods.popSkuGoods_sn,//商品编号
          goods_id: that.childgoods.id,
          goods_sku_id: skuId,
          num: number,
          store_id: that.childgoods.store_id,
        };
      }
      console.info('req',req);
      this.$API.cashier.cart.add.post(req).then(res=>{
        if (res.code == 1) {
          this.$message({
            message: "添加成功~",
            type: "success"
          });
          // getApp().getMyCarList();
          // this.show = false;
          // this.$forceUpdate();

          this.getCartList();//获取购物清单
        }else{
          this.$message.error(res.message);
        }
      }).catch((err) => {
        console.log("🚀 ~ cart ~ err:", err);
      });
    },
    //购物车产品数量加减
    stepMinusHandle(num,cc) {
      console.info('stepMinusHandle',num,cc);
      let that = this;
      
      let goods_id = cc.goods_id;
      let goods_sku_id = cc.goods_sku_id;
      let cart_id = cc.cart_id;
      let obj = that.odata.find((v) => v.id == cart_id);
      console.log("🚀 ~ stepMinusHandle ~ obj:", obj);
      // let num = obj.num - 1;
      if (num != 0) {
        let req = {
          id: cart_id,
          goods_id: goods_id,
          goods_sku_id: goods_sku_id,
          num: num,
        };
        this.$API.cashier.cart.edit.post(req)
          .then((res) => {
            console.log("🚀 ~ editCart ~ res:", res);
            if (res.code == 1) {
              that.getCartList();
            }else{
              this.$message.error(res.message);
            }
          })
          .catch((err) => {
            console.log("🚀 ~ editCart ~ err:", err);
          });
      } else {
        //删除
        let req = {
          id: cart_id,
        };
        this.$API.cashier.cart.delete.post(req)
          .then((res) => {
            console.log("🚀 ~ delCart ~ res:", res);
            if (res.code == 1) {
              that.getCartList();
            }else{
              this.$message.error(res.message);
            }
          })
          .catch((err) => {
            console.log("🚀 ~ delCart ~ err:", err);
          });
      }
    },
    //数量加减
    numberChangeHandle(e) {
      console.log(e.detail);
      console.log(this.childgoods.popStock.match(/\d+/)[0]);
      if (Number(e.detail) > Number(this.childgoods.popStock.match(/\d+/)[0])) {
        this.$message.error("库存不足~");
        
      } else {
        this.childgoods.popNumber = e.detail;
      }
    },
    //规格被选择
    skuTapHandle(item, outer, cc) {
      // this.$set(this.childgoods.spec_list[outer], "selected", cc);
      this.childgoods.spec_list[outer]["selected"] = cc;
      this.changeSku();
    },

    // 更新 detail 的方法
    updateDetail(newContent) {
      this.childgoods = {
        ...newContent
      };
    },
    //修改规格
    changeSku() {
      let arr = this.childgoods.spec_list;
      if (arr.every((item) => item.selected)) {
        console.log("所有规格已选择");
        // 取出item的name和selected，组成{name:selected}格式
        let sku = arr.reduce((acc, cur) => {
          acc[cur.name] = cur.selected;
          return acc;
        }, {});
        let skuObj = this.childgoods.sku.find(
          (item) => JSON.stringify(item.sku_value) === JSON.stringify(sku)
        );
        console.log("🚀 ~ changeSku ~ skuObj:", skuObj);
        let parts = skuObj.price.split(".");
        this.childgoods.popFormatBig = parts[0];
        this.childgoods.popFormatMini = parts[1] ? "." + parts[1] : ".00";
        this.childgoods.popStock = "库存 " + skuObj.stock;
        this.childgoods.popNumber = 1;
        this.childgoods.popSkuGoods_sn = skuObj.goods_sn;
        this.childgoods["skuId"] = skuObj.id;
      } else {
        console.log("还有规格未选择");
      }
    },
    //删除产品
    goodsDeleteHandle(gid, sid) {

				let that = this;
				
				let cid = that.odata
					.filter((v) => v.goods_id == gid && v.goods_sku_id == sid)
					.map((v) => v.id);

				let req = {
					ids: cid,
				};
				this.$API.cashier.cart.delete.post(req)
					.then((res) => {
						console.log("🚀 ~ delCart ~ res:", res);
						if (res.code == 1) {
							that.getCartList();
						}else{
              this.$message.error(res.message);
            }
					})
					.catch((err) => {
						console.log("🚀 ~ delCart ~ err:", err);
					});
    },
    //获取购物车列表
    getCartList(){
      let that = this;
      this.$API.cashier.cart.list.get({page:1,limit:100}).then((res) => {
          console.log("🚀 ~ getCartList ~ res:", res);
          if (res.code == 1) {
            let data = res.data;
            that.odata = data;
            const groupedData = data.reduce((acc, item) => {
              const storeId = item.store_id;
              if (!acc[storeId]) {
                acc[storeId] = {
                  id: storeId,
                  title: item.store.title,
                  cover: item.store.cover,
                  content: [],
                  selected: 0,
                };
              }
              acc[storeId].content.push({
                cart_id: item.id,
                member_id: item.member_id,
                goods_id: item.goods_id,
                goods_sku_id: item.goods_sku_id,
                num: item.num,
                created_at: item.created_at,
                updated_at: item.updated_at,
                goods: item.goods,
                sku: item.sku,
              });
              return acc;
            }, {});
            const result = Object.values(groupedData);

            result.forEach((store) => {
              store.content.forEach((item) => {
                if (item.sku && item.sku.price) {
                  const priceParts = item.sku.price.split(".");
                  const formatBig = priceParts[0];
                  const formatMini =
                    priceParts.length > 1 ? `.${priceParts[1]}` : ".00";
                  item.formatBig = formatBig;
                  item.formatMini = formatMini;
                  item.readyPrice = item.sku.price;
                  item.selected = 0;

                  item.ready_integral = item.sku.integral;//积分
                } else {
                  const priceParts = item.goods.price.split(".");
                  const formatBig = priceParts[0];
                  const formatMini =
                    priceParts.length > 1 ? `.${priceParts[1]}` : ".00";
                  item.formatBig = formatBig;
                  item.formatMini = formatMini;
                  item.readyPrice = item.goods.price;
                  item.selected = 0;

                  item.ready_integral = item.goods.integral;////积分
                }
              });
              const mergedData = Object.values(
                that.mergeObjects(store.content)
              );
              console.log("🚀 ~ result.forEach ~ mergedData:", mergedData);
              store.content = mergedData;
            });
            console.log("🚀 ~ result.forEach ~ result:", result);

            that.listdata = result;
            
          }else{
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log("🚀 ~ getCartList ~ err:", err);
        });

    },
    // 合并购物车相同规格的商品
    mergeObjects(arr) {
      return arr.reduce((acc, curr) => {
        const key = curr.sku ?
          `${curr.goods.id}-${curr.sku.id}` :
          `${curr.goods.id}`;
        if (acc[key]) {
          acc[key].num += curr.num;
        } else {
          acc[key] = {
            ...curr,
            goods: {
              ...curr.goods
            },
            sku: curr.sku ? {
              ...curr.sku
            } : null,
          };
          delete acc[key].id;
        }
        return acc;
      }, {});
    },
    //---规格加入购物车-------------------------------------------------------------------------
    //关闭
    handleClose(done) {
      ElMessageBox.confirm('Are you sure to close this dialog?')
        .then(() => {
          done()
        })
        .catch(() => {
          // catch error
        })
    },
    focusfun(){
      // 自动聚焦到输入框，方便直接扫描
        this.loading = ElLoading.service({
          lock: true,
          text: "请开始扫码识别",
          background: "rgba(255, 255, 255, 0.7)",
        });
        this.$nextTick(() => {
          this.$refs.scannerInput.focus();
        });
        // this.loading.close();
    },
    handleScannerInput(event) {
      const input = event.target;
      clearTimeout(this.typingTimeout);

      // 如果用户手动输入，则设置一个短暂的延迟
      if (this.isTyping) {
        this.typingTimeout = setTimeout(() => {
          this.isTyping = false;


          // 扫描完成后的处理逻辑
          this.scannedCode = input.value;
          console.log('Scanned code:', this.scannedCode);

          console.log('input.value:', input.value );


          if(input.value){
            this.childgoods.goods_sn = input.value;
            this.childgoods.store_id = 0;
            this.addCart("single", "", 1);
          }

          // 清空输入框以便下一次扫描
          input.value = '';
          // 处理扫码后的业务逻辑...

          this.blurfun();

        }, 500); // 假设用户不会连续输入超过500ms
      } else {
        clearTimeout(this.typingTimeout);
        // 扫描完成后的处理逻辑
        this.scannedCode = input.value;
        console.log('Scanned code:', this.scannedCode);

        if(input.value){
          this.childgoods.goods_sn = input.value;
          this.childgoods.store_id = 0;
          this.addCart("single", "", 1);
        }

        console.log('input.value:', input.value );
        // 清空输入框以便下一次扫描
        input.value = '';
        this.blurfun();
        // 处理扫码后的业务逻辑...
      }
    },
    onFocus() {
      // 当输入框获得焦点时，认为用户可能开始手动输入
      this.isTyping = true;
    },
    //失去焦点
    blurfun(){
      this.isTyping = false;
      this.loading.close();
    },
    // 添加和计算商品价格
    addOrderList(goods,index) {
      // 商品是否已经存在于订单列表中
      if(goods.sku.length){
        //规格
        this.dialogVisible = true;
        this.childgoods = goods;
        return false;
      }else{
        //非规格
        this.childgoods = goods;
        this.addCart("single", 0, 1);
        return false;
      }
    },
    
    
    // 全部删除商品  清空购物车
    delAllGoods() {
      // this.odata = [];
			this.listdata =  [];
      this.totalMoney = 0;
      this.totalCount = 0;
      this.totaljifen = 0;
      this.childgoods = {spec_list:[]};


      let req = {
        ids: this.odata.map(product => product.id),
      };
      this.$API.cashier.cart.delete.post(req)
        .then((res) => {
          console.log("🚀 ~ delCart ~ res:", res);
          if (res.code == 1) {
            that.getCartList();
          }else{
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log("🚀 ~ delCart ~ err:", err);
        });
      
    },
    
    // 模拟结账
    checkOut() {
      this.$message.error("程序猿小哥正在开发中~");
      return false;


      if (this.totalCount != 0) {
        this.odata = [];
        this.listdata =  [];
        this.totalMoney = 0;
        this.totalCount = 0;
        this.totaljifen = 0;
        this.childgoods = {spec_list:[]};

        this.$message({
          message: "结账成功,辛苦啦~",
          type: "success"
        });

      } else {
        this.$message.error("店员，没有东西，怎么结账呀~");
      }
    },
    upsearch(){
			this.$refs.table.reload(this.search);
		},
		moreUpsearch(search){
			this.search = search;
			this.upsearch();
		},
		moreSearch(){
			this.dialog.search = true
			this.$nextTick(() => {
				this.$refs.searchBox.open().setData(this.search)
			})
		},
		//表格选择后回调事件
		selectionChange(selection){
			this.selection = selection;
		},
  },
};
</script>
<style scoped>
@import url('./cashierhome.scss');
</style>