<!-- eslint-disable no-empty -->
<template>
    <div class="">
      <el-dialog title="耗材信息" width="60vw" :visible.sync="informationdialogshow" @close="resetHaocaiTable">
        <div class="head-container flex">
          <el-input
            v-model="queryinformation.conTypeId"
            size="small"
            clearable
            placeholder="请输入类型id"
            style="width: 100%"
            class="filter-item"
            @keyup.enter.native="getTableDatainformation"
          />
          <el-input
            v-model="queryinformation.conTypeName"
            size="small"
            clearable
            placeholder="请输入类型名称"
            style="width: 100%"
            class="filter-item"
            @keyup.enter.native="getTableDatainformation"
          />
          <el-input
            v-model="queryinformation.conCode"
            size="small"
            clearable
            placeholder="请输入耗材代码"
            style="width: 100%"
            class="filter-item"
            @keyup.enter.native="getTableDatainformation"
          />
          <el-input
            v-model="queryinformation.conName"
            size="small"
            clearable
            placeholder="请输入耗材名称"
            style="width: 100%"
            class="filter-item"
            @keyup.enter.native="getTableDatainformation"
          />
          <div style="display: flex; justify-content: flex-end;margin-left: 10px">
            <el-button
              style="margin-right: 10px"
              type="primary"
              @click="getTableDatainformation"
              >查询</el-button
            >
            <el-button @click="resetHandleinformation">重置</el-button>
          </div>
        </div>
        <el-table
          ref="haocaiTable"
          :data="tableDatainformation.data"
          v-loading="tableDatainformation.loading"
          @selection-change="haocaiSelectedChange"
          row-key="id"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column prop="id" label="ID" width="50px" />
          <el-table-column label="耗材名称" prop="conName" />
          <el-table-column label="耗材代码" prop="conCode" />
          <el-table-column label="类型名称" prop="conTypeName" />
          <el-table-column label="单位" prop="conUnit" />
          <el-table-column label="库存数量" prop="stockNumber">
            <template v-slot="scope">
              {{ (scope.row.stockNumber - scope.row.stockConsume).toFixed(2) }}
            </template>
          </el-table-column>
  
          <!-- <el-table-column label="单位耗材值" prop="surplusStock" /> -->
          <el-table-column label="" width="200">
            <template v-slot="scope">
              <el-button @click="tableDatainformationtable(scope.row)"
                >确定</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="head-container">
          <el-pagination
            :total="tableDatainformation.total"
            :current-page="tableDatainformation.page + 1"
            :page-size="tableDatainformation.size"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="paginationChangeinformation"
            @size-change="
              (e) => {
                tableDatainformation.size = e;
                tableDatainformation.page = 0;
                getTableDatainformation();
              }
            "
          />
          <div style="display: flex; justify-content: flex-end">
            <el-button
              style="margin-right: 20px"
              @click="haocaiCancel"
              >取消</el-button
            >
            <el-button type="primary" @click="haocaiConfirm">确定</el-button>
          </div>
  
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import Sortable from "sortablejs";
  import dayjs from "dayjs";
  import { upProSort, tbProduct } from "@/api/shop";
  import {
    getviewConSku,
    gettbProductSpec,
    gettbConsInfo,
    posttbProskuCons,
    puttbProskuCon,
    deletetbProskuCon,
  } from "@/api/consumable";
  //缓存耗材选中的数据
  let haocaiSelectedMap = {};
  export default {
    data() {
      return {
        dayjs,
        query: {
          conName: "",
          specSnap: "",
          name: "",
          status: "",
        },
        surplusStocks: "",
        typeEnums: [
          {
            label: "正常",
            value: "1",
          },
          {
            label: "禁用",
            value: "0",
          },
        ],
        dialogshow: false, //弹框显示
        dialogtitle: "", //文字显示
        informationdialogshow: false,
        informationdialogshowedit: false,
        tableData: {
          data: [],
          page: 0,
          size: 30,
          loading: false,
          total: 0,
        },
        queryinformation: {
          conTypeId: "",
          conTypeName: "",
          conCode: "",
          conName: "",
        },
        tableDatainformation: {
          data: [],
          page: 0,
          size: 10,
          loading: false,
          total: 0,
        },
        tableDataskudialogshow: false,
        querytableDatasku: {
          specSnap: "",
          name: "",
          shopName: "",
        },
        tableDatasku: {
          data: [],
          page: 0,
          size: 30,
          loading: false,
          total: 0,
        },
        rules: {},
        // 动态新增选择框-所有数据
        addSelect: [],
        // 筛选集合
        commodityArr: [],
        // 选择耗材的index
        ALLisDistribute: null,
      };
    },
    mounted() {
      this.getTableDatainformation();
    },
    methods: {
        open(){
            this.informationdialogshow=true
        },
        close(){
            this.informationdialogshow=false
        },
      resetCommodityArr(){
        this.commodityArr=[]
        this.$refs.addSelect.resetFields();
      },
      resetHaocaiTable(){
        console.log('close')
        haocaiSelectedMap={}
        console.log(haocaiSelectedMap)
        this.$refs.haocaiTable.clearSelection()
      },
      delGoodsHaocai(haocais,haocaiIndex){
        if(haocais.length===1){
          return
        }
        haocais.splice(haocaiIndex,1)
      },
      //初始化耗材表单选中状态
      initTableSelected(){
        for(let i in haocaiSelectedMap){
              const index=this.tableDatainformation.data.findIndex(v=>v.id==i)
              if(index!=-1&&haocaiSelectedMap[i]){
                  //删除缓存里的id
                  delete haocaiSelectedMap[i]
                  requestAnimationFrame(()=>{
                      this.$refs.haocaiTable.toggleRowSelection(this.tableDatainformation.data[index],haocaiSelectedMap[i])
                  })
              }
          }
      },
      haocaiCancel(){
          this.informationdialogshow = false
      },
      haocaiConfirm(){
            console.log(haocaiSelectedMap)

            this.$emit('confirm',haocaiSelectedMap)
             this.informationdialogshow = false;
            return
          this.commodityArr.forEach((ele) => {
          if (ele.id == this.ALLisDistribute.id) {
            ele.haocais=[]
            let index=-1;
            for(let key in haocaiSelectedMap){
              const item=haocaiSelectedMap[key]
              console.log(item)
              index++
              this.$set(ele.haocais,index,{
                consInfoId:item.id,
                conInfoId:item.id,
                conName:item.conName,
                skuId:ele.id,
                shopId:ele.shopId,
              })
            }
          
          }
        });
        
        this.informationdialogshow = false;
      },
      haocaiSelectedChange(e) {
        const arr = e.filter((v) => v);
        console.log(arr);
        for(let item of this.tableDatainformation.data){
          //判断缓存队列是否有这个id
          const hasCacheIncludes=haocaiSelectedMap.hasOwnProperty(item.id)
          //判断当前选中队列里是否有这个id
          const hasSelectedIncludes=arr.find(v=>v.id==item.id)
          if(hasSelectedIncludes){
            haocaiSelectedMap[item.id] = hasSelectedIncludes;
          }
          if(hasCacheIncludes&&!hasSelectedIncludes){
            delete haocaiSelectedMap[item.id];
  
          }
        }
        console.log(haocaiSelectedMap);
      },
      limitInput(value, name) {
        this.surplusStocks.surplusStock =
          ("" + value) // 第一步：转成字符串
            // .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
  
            .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
  
            .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
  
            .match(/^\d*(\.?\d{0,2})/g)[0] || "";
      },
      handleKeyUp(value, index) {
        console.log(value, index, "体哦傲视1");
        if (value < 0) {
          this.commodityArr[index].surplusStock = value * -1;
        }
      },
      selectShop(res) {
        console.log(res)
        this.$refs.bindHaocai.open(res)
        return
        this.commodityArr = [];
        const haocais= {conName:'',surplusStock:""};
        const arr=res.map(v=>{
          return{...v,haocais:v.skuList.map(sku=>{
            return{...sku,conName:sku.conName||'',surplusStock:sku.surplusStock||''}
          })}
        })
        this.addSelect = res.map(v=>{
          return {...v,haocais:[{...haocais}]}
        })
        this.commodityArr=arr
  
        this.clickdialogframe("add");
  
        return
        res.forEach((ele, i) => {
          // isDistribute1为共享库存-商品，0不共享是多规格
          // 判断是否共享拆分数据到商品和规格集合里
          
          let sname = ele.name;
          if (ele.isDistribute == 1) {
            console.log('单规格')
            ele.specSnap = ele.name;
            ele.conName = ele.conName;
            this.commodityArr.push({...ele,haocais:[{...haocais}]});
            ele.names = sname;
          } else {
            // 规格数据处理
            console.log('多规格')
            ele.skuList.forEach((element, indexs) => {
              if (indexs == 0) {
                element.names = sname;
              }
              element.conInfoId = element.id;
              element.conName = element.conName;
              if (element.specSnap == null) {
                element.specSnap = sname;
              }
              this.commodityArr.push({...element,haocais:[{...haocais}]});
            });
          }
        });
        this.clickdialogframe("add");
      },
      // 选择耗材
      selecthaocai(item) {
        
        this.ALLisDistribute = item;
        this.commodityArr.forEach((ele) => {
          if (ele.id == this.ALLisDistribute.id) {
            console.log(ele.haocais)
            ele.haocais.map(v=>{
              if(v.conInfoId){
                haocaiSelectedMap[v.conInfoId]=v
              }
            })
          }
        });
        this.initTableSelected()
        this.informationdialogshow = true;
        
      },
      //表格拖拽
      tableDrag() {
        const el = document.querySelector(
          "#table_drag .el-table__body-wrapper tbody"
        );
        new Sortable(el, {
          animation: 150,
          onEnd: async (e) => {
            // console.log('拖拽结束===', e);
            if (e.oldIndex == e.newIndex) return;
            let oid = this.tableData.data[e.oldIndex].id;
            let nid = this.tableData.data[e.newIndex].id;
            let ids = this.tableData.data.map((item) => item.id);
            try {
              await upProSort({
                strId: oid,
                endId: nid,
                ids: ids,
              });
              await this.getTableData();
            } catch (error) {
              console.log(error);
            }
          },
        });
      },
      // 重置查询
      resetHandle() {
        this.query.conName = "";
        this.query.specSnap = "";
        this.query.name = "";
        this.query.status = "";
        this.tableData.page = 0;
        this.getTableData();
      },
      resetHandlesku() {
        this.querytableDatasku.specSnap = "";
        this.querytableDatasku.name = "";
        this.querytableDatasku.shopName = "";
        this.tableDatasku.page = 0;
        this.getTableDatasku();
      },
      resetHandleinformation() {
        this.queryinformation.conTypeId = "";
        this.queryinformation.conTypeName = "";
        this.queryinformation.conCode = "";
        this.queryinformation.conName = "";
        this.tableDatainformation.page = 0;
        this.getTableDatainformation();
      },
      // 分页回调
      paginationChange(e) {
        this.tableData.page = e - 1;
        this.getTableData();
      },
      // 获取商品列表
      async getTableData() {
        this.tableData.loading = true;
        try {
          const res = await getviewConSku({
            page: this.tableData.page,
            size: this.tableData.size,
            conName: this.query.conName,
            specSnap: this.query.specSnap,
            name: this.query.name,
            status: this.query.status,
            shopId: localStorage.getItem("shopId"),
          });
          this.tableData.loading = false;
          this.tableData.data = res.content;
          this.tableData.total = res.totalElements;
        } catch (error) {
          console.log(error);
        }
      },
      paginationChangeinformation(e) {
        this.tableDatainformation.page = e - 1;
        this.getTableDatainformation();
      },
      // 获取信息管理
      async getTableDatainformation() {
        this.tableDatainformation.loading = true;
        try {
          const res = await gettbConsInfo({
            page: this.tableDatainformation.page,
            size: this.tableDatainformation.size,
            shopId: localStorage.getItem("shopId"),
            conTypeId: this.queryinformation.conTypeId,
            conTypeName: this.queryinformation.conTypeName,
            conCode: this.queryinformation.conCode,
            conName: this.queryinformation.conName,
          });
          this.tableDatainformation.loading = false;
          this.tableDatainformation.data = res.content;
          this.tableDatainformation.total = res.totalElements;
          this.initTableSelected()
          
        } catch (error) {
          console.log(error);
        }
      },
      // 耗材信息的信息
      tableDatainformationtable(item) {
        this.commodityArr.forEach((ele) => {
         
          if (ele.id == this.ALLisDistribute.id) {
            console.log(ele.haocais)
            ele.haocais[0].consInfoId = item.id;
            ele.haocais[0].conInfoId = item.id;
            ele.haocais[0].conName = item.conName;
            ele.haocais[0].skuId = ele.id;
            ele.haocais[0].shopId = ele.shopId;
            
          }
        });
        this.informationdialogshow = false;
      },
      // 获取商品规格
      async getTableDatasku() {
        this.tableDatasku.loading = true;
        try {
          const res = await tbProduct({
            page: this.tableDatasku.page,
            size: this.tableDatasku.size,
            shopId: localStorage.getItem("shopId"),
            specSnap: this.querytableDatasku.specSnap,
            name: this.querytableDatasku.name,
            sort: "id.desc",
            shopName: this.querytableDatasku.shopName,
          });
          this.tableDatasku.loading = false;
          this.tableDatasku.data = res.content;
          this.tableDatasku.total = res.totalElements;
        } catch (error) {
          console.log(error);
        }
      },
      Changeinformationsku(e) {
        this.tableDatasku.page = e - 1;
        this.getTableDatasku();
      },
      // 弹框修改值  添加  编辑
      clickdialogframe(type, item) {
        if (type == "add") {
          // 添加
          this.dialogtitle = "添加";
          this.$nextTick(() => {
            this.$refs.addSelect.resetFields();
          });
          this.dialogshow = true;
        } else {
          this.informationdialogshowedit = true;
          this.dialogtitle = "编辑";
          this.surplusStocks = item;
        }
      },
      async submitForm(formName) {
        if (this.dialogtitle == "编辑") {
          let { id, surplusStock } = this.surplusStocks;
          await puttbProskuCon({
            id,
            surplusStock,
          });
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.informationdialogshowedit = false;
        } else {
          // isDistribute1为共享库存-商品，0不共享是多规格
          let isgongx = false;
          this.commodityArr.forEach((ele) => {
            ele.haocais.forEach(v=>{
              if (!v.skuId || !v.surplusStock) {
                isgongx = true;
              }
            })
          });
          if (isgongx) {
            this.$message.error("请选择耗材信息与输入耗材值");
            isgongx = false;
            return;
          }
  
          this.commodityArr.forEach((ele) => {
            // ele.skuInfos = ele.skuList;
            console.log(ele)
            ele.skuInfos = ele.haocais;
            ele.productId = ele.id; //商品id
          });
          await posttbProskuCons(this.commodityArr);
         
          // this.addSelect.forEach((ele) => {
          //   // ele.skuInfos = ele.skuList;
          //   console.log(ele)
          //   ele.skuInfos = ele.haocais;
          //   ele.productId = ele.id; //商品id
          // });
          // await posttbProskuCons(this.addSelect);
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.ALLisDistribute = null;
          this.dialogshow = false;
        }
        this.$refs[formName].resetFields();
        this.getTableData();
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 删除商品
      async delTableHandle(ids) {
        try {
          await deletetbProskuCon(ids);
          this.getTableData();
        } catch (error) {
          console.log(error);
        }
      },
    },
  };
  </script>
  
  <style scoped lang="scss">
  .flex{
    display: flex;
    align-content: center;
  }
  .handle {
    font-size: 18px;
    color: #999;
  
    &:hover {
      cursor: grab;
    }
  }
  
  .shop_info {
    display: flex;
  
    .info {
      flex: 1;
      padding-left: 8px;
      display: flex;
      flex-direction: column;
  
      .tag_wrap {
        display: flex;
      }
    }
  }
  .head-container .filter-item{
    margin: 0 5px 0 0;;
  }
  </style>