<template>
  <div class="app-container">
    <!--    客户搜索 -->
    <el-row :gutter="10">
      <el-card class="box-card custom-card">
        <el-col :span="8">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="90px" style="width: 450px">
            <el-row>
              <el-form-item label="客户手机号" prop="phoneNumber">
                <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable @clear="clearAppUserInfo" maxlength="11"
                  @keyup.enter.native="searchUser" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchUser">搜索</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-descriptions :column="2" style="width: 400px">
            <el-descriptions-item label="用户名">{{appUserInfo?appUserInfo.realName:'- -'}}</el-descriptions-item>
            <el-descriptions-item label="手机号" style="width: 100px">{{appUserInfo?appUserInfo.phoneNumber:'- -'}}</el-descriptions-item>
            <el-descriptions-item label="等级">{{appUserInfo?appUserInfo.level:'- -'}}</el-descriptions-item>
            <el-descriptions-item label="余额">
              {{appUserInfo?appUserInfo.rechargeBalance + appUserInfo.giveBalance:'- -'}}
            </el-descriptions-item>
            <el-descriptions-item label="现金">
              {{appUserInfo?appUserInfo.rechargeBalance:'- -'}}
            </el-descriptions-item>
            <el-descriptions-item label="赠送余额">
              {{appUserInfo?appUserInfo.giveBalance:'- -'}}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="5">
          <el-form style="height: 100px;padding-top: 40px;text-align: right" :inline="true" size="small">
            <div>
              <el-form-item label="总件数:" prop="totalClothNum">
                <span>{{calculateTotalCount}}</span>
              </el-form-item>
              <el-form-item label="总金额:" prop="totalPrice">
                <span>{{calculateTotalPrice}}</span>
              </el-form-item>
            </div>
          </el-form>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" style="height: 40px;margin-top: 30px;text-align: center" icon="el-icon-shopping-cart-2" size="small"
            @click="submitCash">收银</el-button>
        </el-col>
      </el-card>
    </el-row>

    <!--  选择商品页面  -->
    <el-row :gutter="10" style="margin-top: 10px">
      <el-col :span="4">
        <div class="head-container-two" :style="{ border: '1px solid #ccc'}">
          <el-table :data="categoryList" :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}" ref="singleTable"
            highlight-current-row @row-click="handleNodeClick">
            <<el-table-column property="categoryName" label="商品分类" />
          </el-table>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="head-column1" :style="{ border: '1px solid #ccc'}">
          <el-table :data="addGoodsList">
            <el-table-column label="编号" align="center" prop="goodsSkuStoreId" />
            <el-table-column label="商品名称" align="center" prop="goodsName" width="200px" />
            <el-table-column label="材料规格" align="center" width="200px" show-overflow-tooltip>
              <template slot-scope="scope">
                <template v-for="(item,index) in scope.row.specVoList">
                  {{index == 0?item.specName+':'+item.specValue:('| ' + item.specName+':'+item.specValue)}}
                </template>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center">
              <template slot-scope="scope">
                <el-input-number v-if="scope.row.goodsSkuStoreId == vo.goodsSkuStoreId" v-for="vo in purchaseCountVOList" :key="vo.goodsSkuStoreId"
                  v-model="vo.count" :step="1" :min="1" :max="scope.row.stock" @change="countPrice" />
              </template>
            </el-table-column>
            <el-table-column label="价格" align="center" prop="salePrice" />
            <!--            <el-table-column label="库存" align="center" prop="stock" />-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-delete-solid" @click="deleteGoods(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="head-column1" style="margin-top: 10px" :style="{ border: '1px solid #ccc'}">
          <el-table v-loading="goodsLoading" :data="goodsList">
            <el-table-column label="编号" align="center" prop="goodsCode" />
            <el-table-column label="商品名称" align="center" prop="goodsName" width="200" />
            <el-table-column label="图片" align="center" prop="goodsImg" width="60">
              <template slot-scope="scope">
                <el-image style="width: 40px; height: 40px" :src="scope.row.goodsImg" :preview-src-list="[scope.row.goodsImg]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="品牌" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.brandId==item.id" v-for="item in brandList" :key="item.id">
                  {{item.brandName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品分类" align="center" prop="goodsCategoryId">
              <template slot-scope="scope">
                <span v-if="scope.row.goodsCategoryId==item.id" v-for="item in categoryList" :key="item.id">
                  {{item.categoryName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否促销" align="center" prop="isSell">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isSell==dict.value" v-for="dict in dict.type.sys_yes_no" :label="dict.value" :key="dict.code">
                  {{dict.label}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-s-shop" @click="selectSpec(scope.row)">选择规格</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParamsGoods.pageNum" :limit.sync="queryParamsGoods.pageSize"
            @pagination="getGoodsList" />
        </div>
      </el-col>
    </el-row>

    <!-- 选择物料页面  -->
    <el-dialog title="商品物料列表" :visible.sync="skuOpen" append-to-body size="60%">
      <div class="head-goods" style="margin-top: 10px" :style="{ border: '1px solid #ccc'}">
        <el-table v-loading="skuLoading" :data="goodsSkuList">
          <el-table-column label="编号" align="center" prop="goodsSkuStoreId" width="200px" />
          <el-table-column label="商品名称" align="center" prop="goodsName" width="200px" />
          <el-table-column label="材料规格" align="center" width="200px">
            <template slot-scope="scope">
              <template v-for="(item,index) in scope.row.specVoList">
                {{index == 0?item.specName+':'+item.specValue:('| ' + item.specName+':'+item.specValue)}}
              </template>
            </template>
          </el-table-column>
          <el-table-column label="价格" align="center" prop="salePrice" />
          <el-table-column label="库存" align="center" prop="stock" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-s-shop" @click="addGoods(scope.row)">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 收银页面  -->
    <el-dialog title="收银" :visible.sync="payOpen" width="50%">
      <el-descriptions title="核对信息" v-if="appUserInfo" :column="3" border :contentStyle="{'text-align': 'center'}">
        <el-descriptions-item label="总件数" :labelStyle="{width: '16%'}" :label-style="{'text-align': 'center'}">{{calculateTotalCount}}
        </el-descriptions-item>
        <el-descriptions-item label="抵扣金额" :labelStyle="{width: '16%'}" :label-style="{'text-align': 'center'}">
          {{payFrom.deductAmount?"￥" + payFrom.deductAmount:"￥" + "0"}}</el-descriptions-item>
        <el-descriptions-item label="卡余额" :labelStyle="{width: '16%'}" :label-style="{'text-align': 'center'}">
          ￥{{  appUserInfo?appUserInfo.rechargeBalance + appUserInfo.giveBalance: "0.00"  }}</el-descriptions-item>

        <el-descriptions-item label="原价">{{calculateTotalPrice}}</el-descriptions-item>
        <el-descriptions-item label="折后金额">{{ calculatePayMoney }}</el-descriptions-item>
        <!--        <el-descriptions-item label="现有积分">{{appUserInfo.pointBalance}}</el-descriptions-item>-->
      </el-descriptions>
      <template v-if="calculateTotalCount>0">
        <el-form ref="payFrom" :model="payFrom" label-width="80px" style="margin-top: 20px">
          <el-row :gutter="10">
            <el-card style="width: 90%">
              <el-col :span="24">
                <el-descriptions title="优惠信息"></el-descriptions>
              </el-col>
              <el-col :span="24">
                <el-form-item label="抵扣现金券（元）" label-width="130px" prop="deductAmount">
                  <el-input-number :min="1" :max="9999999" :controls="false" style="width: 200px" v-model.number="payFrom.deductAmount">
                  </el-input-number>
                </el-form-item>
              </el-col>
            </el-card>
          </el-row>
          <el-row :gutter="10">
            <el-card style="width: 90%;margin-top: 15px">
              <el-col :span="24">
                <el-form-item label="支付方式" prop="payType">
                  <el-radio-group v-model="payFrom.payType" style="width: 400px" @input="changePayType">
                    <el-radio-button label="3">余额</el-radio-button>
                    <el-radio-button label="2">现金</el-radio-button>
                    <el-radio-button label="0">微信</el-radio-button>
                    <el-radio-button label="1">支付宝</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <div v-if="payFrom.payType">
                <el-col :span="8">
                  <el-descriptions :column="2" style="width: 400px" v-if="payFrom.payType=='3' && appUserInfo">
                    <el-descriptions-item label="客户姓名">{{appUserInfo?appUserInfo.realName:'- -'}}</el-descriptions-item>
                    <el-descriptions-item label="余额">
                      ￥{{appUserInfo?appUserInfo.rechargeBalance + appUserInfo.giveBalance:'0.00'}}
                    </el-descriptions-item>
                  </el-descriptions>
                </el-col>
                <el-col :span="12" v-if="payFrom.payType=='2'">
                  <el-form-item label="实收现金（元）" label-width="120px" prop="thisPayMoney">
                    <el-input-number :min="1" :max="9999999" :controls="false" v-model="payFrom.thisPayMoney"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="payFrom.payType=='2'">
                  <el-form-item label="找零:" label-width="120px">
                    <span>{{payFrom.thisPayMoney && payFrom.thisPayMoney - payMoney >= 0?payFrom.thisPayMoney - payMoney : '0' }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="payFrom.payType=='0'">
                  <el-form-item label="微信付款条形码" label-width="120px" prop="wxBarcode">
                    <el-input style="width: 200px" v-model="payFrom.wxBarcode"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="payFrom.payType=='1'">
                  <el-form-item label="支付宝付款条形码" label-width="130px" prop="aliPayBarcode">
                    <el-input style="width: 200px" v-model="payFrom.aliPayBarcode"></el-input>
                  </el-form-item>
                </el-col>
              </div>
            </el-card>
          </el-row>
          <el-row :gutter="10">
            <div>
              <el-button type="primary" @click="submitSettlement" style="margin-left: 3%;margin-top: 20px">结算</el-button>
            </div>
          </el-row>
        </el-form>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsListToGoodsRetail, getGoodsSkuListToGoodsRetail, purchaseListSku } from '@/api/core/sku'
import { listCategory } from '@/api/core/category'
import { findUserByPhoneNumber } from '@/api/app/user'
import { listBrand } from '@/api/core/brand'
import { insertRetailOrderGoods, getGoods } from '@/api/order/goods'
import { getLodop } from "@/utils/lodopUtils";

export default {
  name: "goodsRetail",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 客户信息
      appUserInfo: null,
      // 商品列表等待
      goodsLoading: false,
      // 物料列表等待
      skuLoading: false,
      // 总条数
      total: 0,

      // 弹出层标题
      title: "",
      // 是否显示弹出层 物料页面弹框
      skuOpen: false,
      // 收银支付页面弹框
      payOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 查询分类+品牌的查询参数
      queryParams2: {
        pageNum: 1,
        pageSize: 9999,
        status: '0',
        goodsType: null,
      },
      // 查询参数
      queryParamsGoods: {
        pageNum: 1,
        pageSize: 10,
      },
      // 支付表单参数
      payFrom: {
      },
      // 表单校验
      rules: {
      },
      goodsType: null,
      // 分类id
      goodsCategoryId: null,
      // 可选商品集合
      goodsList: null,
      // 可选商品物料集合
      goodsSkuList: null,
      // 已选商品集合
      addGoodsList: [],
      // 左侧分类集合
      categoryList: null,
      // 品牌list
      brandList: {},
      // 自定义一个计算数量的临时对象集合
      purchaseCountVOList: [],
      // 总金额
      totalPrice: 0,
      // 总件数
      totalCount: 0,
      // 提交的参数对象
      submitGoodsOrderDTO: {},
      // 需要支付的金额
      payMoney: null,

      LODOP: null,
      number: 1,
      pointerList: [],
      userInfoVO: null,
    };
  },
  created() {
    this.handleUser();
    this.goodsType = this.getUrlParam('goodsType');
    this.getCategoryList();
    this.getBrandList();
  },
  mounted() {
    this.number = 1;
    const printerTime = setInterval(() => {
      this.LODOP = getLodop();
      this.number++
      if (this.number == 25) {
        clearInterval(printerTime);
      }
      if (this.LODOP) {
        clearInterval(printerTime);
      }
    }, 200)

    this.pointerList = JSON.parse(this.$cache.local.get("printerSeting"));
  },
  computed: {
    calculateTotalCount() {
      this.totalCount = 0;
      this.addGoodsList.forEach(vo => {
        let number = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == vo.goodsSkuStoreId).count;
        this.totalCount = this.totalCount + number;
      });
      return this.totalCount;
    },
    calculateTotalPrice() {
      this.totalPrice = 0;
      this.addGoodsList.forEach(vo => {
        let number = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == vo.goodsSkuStoreId).count;
        this.totalPrice = this.totalPrice + (number * vo.salePrice);
      });
      return this.totalPrice;
    },
    calculatePayMoney() {
      this.payMoney = this.payFrom.deductAmount ? this.totalPrice - this.payFrom.deductAmount : this.totalPrice;
      return this.payMoney;
    }
  },

  methods: {
    handleUser() {
      this.userInfoVO = this.getUserInfo();
    },
    // 切换支付方式
    changePayType() {
      delete this.payFrom.thisPayMoney
    },
    // 收银
    submitCash() {
      if (this.appUserInfo == null) {
        this.$message.error("请选择客户");
        return;
      }
      if (this.calculateTotalCount == 0) {
        this.$message.error("请选择商品");
      }
      this.payOpen = true;
    },
    // 清空用户数据
    clearAppUserInfo() {
      this.appUserInfo = null;
    },
    //搜索用户
    searchUser() {
      if (this.queryParams.phoneNumber == null || this.queryParams.phoneNumber == '') {
        return;
      }
      findUserByPhoneNumber(this.queryParams).then(res => {
        this.appUserInfo = res.data;
      })
    },
    // 获取商品分类列表
    getCategoryList() {
      listCategory({ ...this.queryParams2, ...{ goodsType: this.goodsType } }).then(response2 => {
        this.categoryList = response2.rows;
      });
    },
    // 获取品牌
    getBrandList() {
      listBrand({ ...this.queryParams2, ...{ goodsType: this.goodsType } }).then(response1 => {
        this.brandList = response1.rows;
      });
    },
    // 已选择列表中，删除商品按钮
    deleteGoods(row) {
      this.addGoodsList = this.addGoodsList.filter((item) => {
        return item.goodsSkuStoreId !== row.goodsSkuStoreId;
      })
      this.purchaseCountVOList = this.purchaseCountVOList.filter((item) => {
        return item.goodsSkuStoreId !== row.goodsSkuStoreId;
      })
    },
    // 未选列表中，添加按钮
    addGoods(row) {
      if (row.stock <= 0) {
        this.$message.error("库存不足，无法添加");
        return;
      }
      if (this.addGoodsList.length > 0) {
        let match = this.addGoodsList.findIndex(item => item.goodsSkuStoreId == row.goodsSkuStoreId)
        // -1 : findIndex没找到
        if (match != '-1') {
          let purchaseVo = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == row.goodsSkuStoreId);
          if (purchaseVo.count >= row.stock) {
            this.$message.error("库存不足");
            return;
          }
          purchaseVo.count++;
          this.skuOpen = false;
          this.$forceUpdate();
          return;
        }
      }
      this.addGoodsList.push(row);
      this.purchaseCountVOList.push({
        'goodsSkuStoreId': row.goodsSkuStoreId,
        'goodsCategoryId': this.goodsCategoryId,
        'goodsCategoryName': this.categoryList.find(item => item.id == this.goodsCategoryId).categoryName,
        'count': 1
      })
      this.skuOpen = false;
      this.$forceUpdate();
    },
    // 操作数量增减时，计算价格
    countPrice() {
      this.totalPrice = 0;
      this.totalCount = 0;
      this.addGoodsList.forEach(vo => {
        let number = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == vo.goodsSkuStoreId).count;
        this.totalPrice = this.totalPrice + (number * vo.salePrice);
        this.totalCount = this.totalCount + number;
      })
    },
    // 左侧商品分类列表，单击事件
    handleNodeClick(data) {
      this.goodsCategoryId = data.id;
      this.getGoodsList();
    },
    // 获取商品列表
    getGoodsList() {
      this.goodsLoading = true;
      if (this.goodsCategoryId == null) {
        this.goodsList = [];
        this.goodsLoading = false;
        return;
      }
      this.queryParamsGoods.goodsCategoryId = this.goodsCategoryId;
      getGoodsListToGoodsRetail(this.queryParamsGoods).then(response => {
        this.goodsList = response.data;
        this.total = response.data.length;
        this.goodsLoading = false;
      });
    },
    // 选择商品规格
    selectSpec(row) {
      this.skuLoading = true;
      getGoodsSkuListToGoodsRetail(row.id).then(response => {
        this.goodsSkuList = response.data;
        this.skuLoading = false;
        this.skuOpen = true;
      });
    },
    // 结算
    submitSettlement() {
      this.$confirm('是否确认结算？').then(() => {
        if (this.totalCount == 0) {
          this.$message.error("请选择商品");
          return;
        }
        if (this.payFrom.payType == null || this.payFrom.payType == '') {
          this.$message.error("请选择支付方式");
          return;
        }
        if (this.payFrom.deductAmount != null || this.payFrom.deductAmount != '') {
          if (this.payFrom.deductAmount > this.payMoney) {
            this.$message.error("抵扣金额不能大于支付金额");
            return;
          }
        }
        if (this.payFrom.payType == '1') {
          if (this.appUserInfo.rechargeBalance + this.appUserInfo.giveBalance < this.payMoney) {
            this.$message.error("用户余额不足");
            return;
          }
        }
        if (this.payFrom.payType == '2') {
          if (this.payFrom.thisPayMoney < this.payMoney) {
            this.$message.error("现金金额不够支付");
            return;
          }
        }
        this.submitGoodsOrderDTO = {};
        // 设置订单基础信息
        this.submitGoodsOrderDTO.totalPrice = this.totalPrice;
        this.submitGoodsOrderDTO.goodsType = this.goodsType;
        this.submitGoodsOrderDTO.deductAmount = this.payFrom.deductAmount;
        this.submitGoodsOrderDTO.appUserId = this.appUserInfo.id;
        this.submitGoodsOrderDTO.payAmount = this.payMoney;
        this.submitGoodsOrderDTO.payType = this.payFrom.payType;
        // 设置订单商品物料信息
        this.submitGoodsOrderDTO.retailGoodsVOList = [];
        this.addGoodsList.forEach(vo => {
          let purchaseVO = this.purchaseCountVOList.find(item => item.goodsSkuStoreId == vo.goodsSkuStoreId)
          let purchaseGoodsVO = {};
          purchaseGoodsVO.skuId = vo.id;
          purchaseGoodsVO.goodsId = vo.goodsId;
          purchaseGoodsVO.goodsName = vo.goodsName;
          purchaseGoodsVO.goodsImg = vo.goodsImg;
          purchaseGoodsVO.goodsCategoryId = purchaseVO.goodsCategoryId;
          purchaseGoodsVO.goodsCategoryName = purchaseVO.goodsCategoryName;
          purchaseGoodsVO.marketPrice = vo.salePrice;
          purchaseGoodsVO.buyNum = purchaseVO.count;
          purchaseGoodsVO.skuName = '';
          vo.specVoList.forEach(spec => {
            purchaseGoodsVO.skuName = purchaseGoodsVO.skuName + spec.specName + ':' + spec.specValue + ' '
          });
          this.submitGoodsOrderDTO.retailGoodsVOList.push(purchaseGoodsVO);
        });

        insertRetailOrderGoods(this.submitGoodsOrderDTO).then(response => {
          this.$modal.msgSuccess("结算完成");
          this.addGoodsList = [];
          this.purchaseCountVOList = [];
          this.submitGoodsOrderDTO = {};
          this.searchUser();
          this.payOpen = false;
          this.btn_lodop(response.data.orderId);
        });
      }).catch(() => { this.payOpen = false; });
    },
    btn_lodop(id) {
      if (!this.LODOP) {
        this.$modal.msgError("请安装打印机软件");
        return
      }

      let p_name = '';

      this.pointerList.forEach(pointer => {
        if (pointer.printType == 0) {
          p_name = pointer.printName
        }
      })

      getGoods(id).then((res) => {
        if (this.userInfoVO.userType == '02') {
          const obj = {
            name: this.userInfoVO.storeName,
            contactPhone: this.userInfoVO.phonenumber,
            user: this.userInfoVO.nickName,
          }
          res.data.sysOrg = obj
        }
        res.data.newTime = this.formatDates(new Date(), 1)
        this.goodsPrinter(this.LODOP, res.data, p_name)
      });
    },
  }
};
</script>
<style>
.head-container-two {
    height: calc(100vh - 250px);
    display: block;
    overflow-y: scroll;
}
.head-column1 {
    height: calc(50vh - 130px);
    display: block;
    overflow-y: scroll;
}
.head-goods {
    height: auto;
    display: block;
    overflow-y: scroll;
}
.box-shadow {
    font-size: 18px;
}
</style>
