<!-- eslint-disable no-empty -->
<template>
  <div class="app-container">
    <div class="head-container">
      <div class="row_wrap">
        <div class="row">
          <!-- <el-input
            v-model="query.conTypeId"
            size="small"
            clearable
            placeholder="请输入类型id"
            style="width: 150px"
            @keyup.enter.native="getTableData"
          /> -->
          <div style="width: 150px">
            <el-select v-model="query.conTypeId" placeholder="请选择耗材分类" style="width: 100%">
              <el-option :label="item.conTypeName" :value="item.id" v-for="item in tableDatatype.data"
                :key="item.conTypeId" />
            </el-select>
          </div>
          <!--<el-input v-model="query.conTypeName" size="small" clearable placeholder="请输入类型名称" style="width: 150px"
            @keyup.enter.native="getTableData" />
          <el-input v-model="query.conCode" size="small" clearable placeholder="请输入耗材代码" style="width: 150px"
            @keyup.enter.native="getTableData" /> 
            <el-select v-model="query.status" placeholder="请选择商品规格">
            <el-option :label="item.label" :value="item.value" v-for="item in typeEnums" :key="item.label" />
          </el-select>-->
          <el-input v-model="query.conName" size="small" clearable placeholder="请输入耗材名称" style="width: 150px"
            @keyup.enter.native="getTableData" />
          <el-date-picker v-model="query.createdAt" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>

          <el-button type="primary" @click="getTableData">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
        <div class="row">
          <!-- <el-button type="primary" icon="el-icon-plus" @click="clickdialogframe('add')">添加</el-button>
          <el-button @click="routerGo('operation_in')">入库</el-button>
          <el-button @click="routerGo('operation_out')">出库</el-button>
          <el-button @click="$router.push({ name: 'type' })">分类管理</el-button>
          <el-button @click="$router.push({ name: 'supplier_manage' })">供应商管理</el-button>
          <el-button icon="el-icon-download" :loading="downloadLoading" @click="protHandle">导出耗材</el-button>
          <el-button icon="el-icon-upload2" :loading="uploadLoading" @click="dialogVisible = true">导入耗材</el-button> -->
          <el-select clearable v-model="query.sort" @change="getTableData" placeholder="排序">
            <el-option label="创建时间" value="createTime,desc" />
            <el-option label="数量由低到高" value="balance,asc" />
          </el-select>
        </div>

      </div>
      <div class="row_wrap" style="margin-top: 12px">
        <div class="row">
          <el-button type="primary" icon="el-icon-plus" @click="clickdialogframe('add')">添加</el-button>
          <el-button @click="$router.push({ name: 'operation_in' })">入库</el-button>
          <el-button @click="$router.push({ name: 'operation_out' })">出库</el-button>
          <!-- <el-button @click="$router.push({ name: 'cons_record' })">耗材记录</el-button> -->
          <el-button @click="$router.push({ name: 'type' })">分类管理</el-button>
          <el-button @click="$router.push({ name: 'supplier_manage' })">供应商管理</el-button>
        </div>
        <!-- <div class="row">
          <el-select clearable v-model="query.sort" @change="getTableData" placeholder="排序">
            <el-option label="创建时间" value="createTime,desc" />
            <el-option label="数量由低到高" value="balance,asc" />
          </el-select>
        </div> -->
      </div>
    </div>
    <template>
      <div class="box">
        <div class="boxitem">
          <img src="@/assets/images/data_home_item1_icon.png" />
          <div class="boxitem_s">
            <div class="boxitem_ses">
              <div class="es">
                <div class="e">耗材种数</div>
                <div class="s" style="color: #333333;">{{ tableData.total }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="boxitem">
          <img src="@/assets/images/data_home_item1_icon.png" />
          <div class="boxitem_s">
            <div class="boxitem_ses">
              <div class="es">
                <div class="e">增加数量:</div>
                <div class="s"
                  @click="stockData.column = 'addCountNumber', stockData.size = 10, stockData.page = 0, gettbConsInfoFlowstock()">
                  {{
                    tongji.addCountNumber }}</div>
              </div>
            </div>
            <div class="boxitem_ses">
              <div class="es">
                <div class="e">手动增加:</div>
                <div class="s"
                  @click="stockData.column = 'addNumber', stockData.size = 10, stockData.page = 0, gettbConsInfoFlowstock()">
                  {{ tongji.addNumber }}
                </div>
              </div>
              <div class="es">
                <div class="e">入库:</div>
                <div class="s"
                  @click="stockData.column = 'stockInNumber', stockData.size = 10, stockData.page = 0, gettbConsInfoFlowstock()">
                  {{
                    tongji.stockInNumber }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="boxitem">
          <img src="@/assets/images/data_home_item1_icon.png" />
          <div class="boxitem_s">
            <div class="boxitem_ses">
              <div class="es">
                <div class="e">减少数量:</div>
                <div class="s"
                  @click="stockData.column = 'subCountNumber', stockData.size = 10, stockData.page = 0, gettbConsInfoFlowstock()">
                  {{
                    tongji.subCountNumber }}</div>
              </div>
            </div>
            <div class="boxitem_ses">
              <div class="es">
                <div class="e">手动减少:</div>
                <div class="s"
                  @click="stockData.column = 'subNumber', stockData.size = 10, stockData.page = 0, gettbConsInfoFlowstock()">
                  {{ tongji.subNumber }}
                </div>
              </div>
              <div class="es">
                <div class="e">消耗:</div>
                <div class="s"
                  @click="stockData.column = 'saleNumber', stockData.size = 10, stockData.page = 0, gettbConsInfoFlowstock()">
                  {{ tongji.saleNumber
                  }}
                </div>
              </div>
              <div class="es">
                <div class="e">报损:</div>
                <div class="s"
                  @click="stockData.column = 'lossNumber', stockData.size = 10, stockData.page = 0, gettbConsInfoFlowstock()">
                  {{ tongji.lossNumber
                  }}
                </div>
              </div>
              <div class="es">
                <div class="e">出库:</div>
                <div class="s"
                  @click="stockData.column = 'stockOutNumber', stockData.size = 10, stockData.page = 0, gettbConsInfoFlowstock()">
                  {{
                    tongji.stockOutNumber }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- 动态信息 出库  报损  消耗  手动减少  减少数量  入库  手动增加  增加数量  现有数量-->
    <el-dialog :title="variabilitytitle" :visible.sync="variabilityshow" width="75%">
      <div class="head-container">
        <el-table ref="table" :data="stockData.data" v-loading="stockData.loading" row-key="id" height="450">
          <!-- 共存前面 -->
          <el-table-column label="耗材名称" prop="conName" />
          <el-table-column label="原有库存" prop="balance">
            <template v-slot="scope">
              <span>{{ scope.row.balance > 0 ? (scope.row.balance + (scope.row.bizType == '-' ?
                scope.row.amount : -scope.row.amount)).toFixed(2) : (Number(scope.row.balance) +
                  Number(scope.row.amount)).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="变动后库存" prop="balance"></el-table-column>
          <el-table-column label="库存变动数量" prop="amount">
            <template v-slot="scope">
              <span :class="{ red: scope.row.bizType == '-' }">{{ scope.row.bizType }}{{ scope.row.amount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作类型" prop="bizName" />
          <el-table-column v-if="variabilitytitle == '消耗'" label="订单编号" prop="orderNo">
            <template v-slot="scope">
              <div>
                <el-button type="text" @click="toGoodslist(scope.row.orderNo)">{{ scope.row.orderNo }}</el-button>
              </div>
            </template>
          </el-table-column>

          <!-- 减少数量 -->
          <el-table-column v-if="variabilitytitle == '报损'" label="图片" prop="coverImg" />
          <!-- 尾巴 -->
          <el-table-column v-if="variabilitytitle != '消耗'" label="操作人" prop="operator" />
          <el-table-column v-if="variabilitytitle != '消耗'" label="备注" prop="remark" />
          <el-table-column label="操作时间" prop="createTime"></el-table-column>

          <!-- <el-table-column label="现有库存" prop="balance" />
          <el-table-column label="业务说明" prop="bizName" />
          <el-table-column label="创建时间" prop="createTime"></el-table-column> -->
        </el-table>
      </div>
      <div class="head-container">
        <el-pagination :total="stockData.total" :current-page="stockData.page + 1" :page-size="stockData.size"
          layout="total, sizes, prev, pager, next, jumper" @current-change="wstockChange" @size-change="(e) => {
            stockData.size = e;
            stockData.page = 0;
            gettbConsInfoFlowstock();
          }" />
      </div>
    </el-dialog>
    <!-- <div class="head-container">
      <el-row>
        <el-col>
          <el-button type="primary" icon="el-icon-plus" @click="clickdialogframe('add')">添加</el-button>
        </el-col>
      </el-row>
    </div> -->
    <div class="head-container" id="table_drag">
      <el-table ref="table" :data="tableData.data" v-loading="tableData.loading" row-key="id">
        <el-table-column label="耗材名称" prop="conName" style="width: 100px;">
          <template v-slot="scope">
            <!-- <div v-if="scope.row.editNYD == 1">
              <el-input v-model="scope.row.conName" placeholder="请输入内容"
                @blur="conNameClick(scope.row)"></el-input>
            </div> -->
            <span>
              {{ scope.row.conName }}
            </span>
            <!-- <i class="el-icon-edit" @click="scope.row.editNYD = 1"></i> -->
            <i class="el-icon-edit" @click="editorHandle(scope.row)"></i>
          </template>
        </el-table-column>
        <!-- <el-table-column label="分类名称" prop="conTypeName"></el-table-column> -->
        <el-table-column label="单位" prop="conUnit">
          <template v-slot="scope">
            <!-- <div v-if="scope.row.editNYD == 2">
              <el-input v-model="scope.row.conUnit" placeholder="请输入内容" @blur="conNameClick(scope.row)"></el-input>
            </div>
            <span v-else>
              {{ scope.row.conUnit }}
            </span>
            <i class="el-icon-edit" @click="scope.row.editNYD = 2"></i> -->
            <span>
              {{ scope.row.conUnit }}
            </span>
            <i class="el-icon-edit" @click="editorHandles(scope.row)"></i>
          </template>

        </el-table-column>
        <!-- <el-table-column label="现有库存">
          <template v-slot="scope">
            <span :class="[computedClass(scope.row.balance)]"> {{ scope.row.balance }}</span>
          </template>
        </el-table-column>
       <el-table-column label="耗材消耗" prop="conConsume" />
        <el-table-column label="耗材入库" prop="conIn" />
        <el-table-column label="耗材出库" prop="conOut" />
        <el-table-column label="耗材反还" prop="conReturn" />-->

        <el-table-column label="所属商品">
          <template v-slot="scope">
            <div class="goodslang">
              <div class="goods-list">
                <el-button v-for="(item) in scope.row.product" @click="toGoods(item.id)" :key="item.productId"
                  type="text">{{
                    item.name }}</el-button><span v-if="scope.row.product.length > 1">,</span>
              </div>
              <el-dropdown trigger="click" v-if="scope.row.product.length > 1" @command="toGoods">
                <span class="el-dropdown-link" style="color: blue;">
                  <i class="el-icon-caret-bottom el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item class="clearfix" v-for="(item) in scope.row.product" :key="item.id"
                    :command="item.id">
                    {{ item.name }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
        <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="conWarning">
          <template v-slot="scope">
            <!-- <div v-if="scope.row.editNYD == 3">
              <el-input v-model="scope.row.conWarning" placeholder="请输入内容" @blur="conNameClick(scope.row)"></el-input>
            </div>
            <span v-else>
              {{ scope.row.conWarning }}
            </span>
            <i class="el-icon-edit" @click="scope.row.editNYD = 3"></i> -->
            <span>
              {{ scope.row.conWarning }}
            </span>
            <i class="el-icon-edit" @click="editorHandle(scope.row)"></i>
          </template>
        </el-table-column>
        <el-table-column label="库存开关" prop="conReturn">
          <template v-slot="scope">
            <el-switch v-model="scope.row.isCheck" active-value="1" inactive-value="0"
              @change="showChange($event, scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- <el-table-column label="状态" prop="status">
          <template v-slot="scope">
            <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
              @change="changeswitchstatus(scope.row)"></el-switch>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="创建时间" prop="createTime" width="200"> </el-table-column> -->
        <el-table-column label="操作" width="250" fixed="right">
          <template v-slot="scope">
            <el-button type="text" @click="editorHandle(scope.row)">编辑</el-button>
            <!-- <el-button type="text" @click="clicksee(scope.row)" style="margin-left: 10px !important">耗材记录</el-button> -->
            <el-button type="text" size="mini" style="margin-left: 10px !important"
              @click="$refs.AddConsTakin.show(scope.row)">耗材盘点</el-button>
            <!-- <el-button style="margin-left: 10px !important" type="text" @click="lookDetail(scope.row)">查看详情</el-button> -->
            <!-- <el-button type="text" icon="el-icon-rank">排序</el-button> -->
            <!-- <el-button type="text" @click="clickdialogfadd(scope.row)"
              style="margin-left: 10px !important;">入库</el-button> -->
            <!-- <el-button type="text" icon="el-icon-edit" @click="clickdialogframe('edit', scope.row)">编辑</el-button> -->
            <!-- <el-popconfirm title="确定删除吗？" @confirm="delTableHandle([scope.row.id])">
              <el-button type="text" icon="el-icon-delete" style="margin-left: 20px !important;"
                slot="reference">删除</el-button>
            </el-popconfirm> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="head-container">
      <el-pagination :total="tableData.total" :current-page="tableData.page + 1" :page-size="tableData.size"
        layout="total, sizes, prev, pager, next, jumper" @current-change="paginationChange" @size-change="(e) => {
          tableData.size = e;
          tableData.page = 0;
          getTableData();
        }
          " />
    </div>
    <!-- 耗材入库 -->
    <el-dialog title="耗材入库" :visible.sync="libraryshow">
      <el-form :inline="true" ref="reflibrary" :model="libraryshowdata" :rules="ruleslibrary" class="demo-form-inline">
        <el-form-item label="耗材入库数量" prop="stockNumber">
          <el-input v-model.number="libraryshowdata.stockNumber" type="number" placeholder="请输入单位"></el-input>
        </el-form-item>
        <el-form-item style="display: flex; justify-content: flex-end">
          <el-button @click="libraryshow = false">取 消</el-button>
          <el-button type="primary" @click="clickdialoglibraryshow('reflibrary')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改和增加 -->
    <el-dialog :title="dialogtitle" :visible.sync="dialogshow" width="80%">
      <template v-if="dialogtitle != '编辑'">
        <div v-for="(item, index) in ruleForms" :key="index">
          <el-form :inline="true" :ref="'refruleForm' + index" :model="item" :rules="rules" class="demo-form-inline">
            <el-form-item label=" ">
              <i class="el-icon-remove-outline color-danger" @click="ruleFormsReduce(index)"></i>
            </el-form-item>
            <el-form-item label="耗材信息名称" prop="conName">
              <el-input v-model="item.conName" placeholder="请输入耗材信息名称"></el-input>
            </el-form-item>
            <el-form-item label="耗材类型" prop="conTypeId">
              <el-select v-model="item.conTypeId" placeholder="请选择"
                @change="selectChange($event, 'refruleForm' + index, 'conTypeId')">
                <el-option v-for="option in tableDatatype.data" :key="option.conTypeId" :label="option.conTypeName"
                  :value="option.id">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item
          label="耗材类型"
          prop="conNames"
          v-if="dialogtitle == '添加'"
        >
          <el-input
            v-model="ruleForm.conNames"
            placeholder="请输耗材信息名称"
            disabled
          ></el-input>
        </el-form-item>-->
            <!-- <el-form-item v-if="dialogtitle == '添加'">
          <el-button type="primary" @click="typedialogshow = true"
            >去选择</el-button
          >
        </el-form-item>  -->

            <el-form-item label="单位" prop="conUnit">
              <el-input v-model="item.conUnit" placeholder="请输入单位"></el-input>
            </el-form-item>
            <!-- <el-form-item label="耗材信息代码" prop="conCode">
          <el-input
            v-model="ruleForm.conCode"
            placeholder="请输入耗材信息代码"
          ></el-input>
        </el-form-item> -->
            <el-form-item label="耗材价格">
              <el-input v-model="item.price" placeholder="请输入耗材价格"></el-input>
            </el-form-item>
            <el-form-item label="预警值">
              <el-input v-model="item.conWarning" placeholder="请输入耗材预警值"></el-input>
            </el-form-item>

            <el-form-item label=" ">
              <i class="el-icon-circle-plus-outline color-success" @click="ruleFormsAdd(index)"></i>
            </el-form-item>
            <!-- <el-form-item label="单位耗材值" prop="surplusStock">
          <el-input v-model="ruleForm.surplusStock" placeholder="请输入单位耗材值"></el-input>
        </el-form-item> -->
          </el-form>
        </div>

        <div style="display: flex; justify-content: flex-end">
          <el-button @click="dialogshow = false">取 消</el-button>
          <el-button type="primary" @click="submitForms()">
            确 定
          </el-button>
        </div>
      </template>

      <template v-else>
        <el-form :inline="true" ref="refruleForm" :model="ruleForm" :rules="rules" class="demo-form-inline">

          <!-- <el-form-item label="单位" prop="conUnit" v-if="dialogtitle == '添加'">
          <el-input v-model="ruleForm.conUnit" placeholder="请输入单位"></el-input>
        </el-form-item>
        <el-form-item label="耗材类型" prop="conTypeId" v-if="dialogtitle == '添加'">
          <el-select v-model="ruleForm.conTypeId" placeholder="请选择">
            <el-option v-for="item in tableDatatype.data" :key="item.conTypeId" :label="item.conTypeName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
          <!-- <el-form-item
          label="耗材类型"
          prop="conNames"
          v-if="dialogtitle == '添加'"
        >
          <el-input
            v-model="ruleForm.conNames"
            placeholder="请输耗材信息名称"
            disabled
          ></el-input>
        </el-form-item>-->
          <!-- <el-form-item v-if="dialogtitle == '添加'">
          <el-button type="primary" @click="typedialogshow = true"
            >去选择</el-button
          >
        </el-form-item>  -->
          <el-form-item label="耗材信息名称" prop="conName">
            <el-input v-model="ruleForm.conName" placeholder="请输入耗材信息名称"></el-input>
          </el-form-item>
          <!-- <el-form-item label="耗材信息代码" prop="conCode">
          <el-input
            v-model="ruleForm.conCode"
            placeholder="请输入耗材信息代码"
          ></el-input>
        </el-form-item> -->
          <el-form-item label="耗材价格">
            <el-input v-model="ruleForm.price" placeholder="请输入耗材价格"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="conUnit">
            <el-input v-model="ruleForm.conUnit" placeholder="请输入单位"></el-input>
          </el-form-item>
          <el-form-item label="预警值">
            <el-input v-model="ruleForm.conWarning" placeholder="请输入耗材预警值"></el-input>
          </el-form-item>
          <!-- <el-form-item label="状态" v-if="dialogtitle == '编辑'">
            <el-switch v-model="ruleForm.status" active-value="1" inactive-value="0"></el-switch>
          </el-form-item> -->
          <!-- <el-form-item label="单位耗材值" prop="surplusStock">
          <el-input v-model="ruleForm.surplusStock" placeholder="请输入单位耗材值"></el-input>
        </el-form-item> -->
          <el-form-item style="display: flex; justify-content: flex-end">
            <el-button @click="dialogshow = false">取 消</el-button>
            <el-button type="primary" @click="submitForm('refruleForm')">
              确 定
            </el-button>
          </el-form-item>
        </el-form>
      </template>
    </el-dialog>
    <!-- 单位修改 -->
    <el-dialog :title="unitItem ? unitItem.conName : ''" @open="closeande" :visible.sync="dialogtitleunit" width="40%">
      <template>
        <div class="unitStyle unitWidth">
          <div>主单位</div>
          <div>{{ unitItem ? unitItem.conUnit : '' }}</div>
          <div style="display: flex;align-items: center;" @click="switchzhufu = 1">
            <div style="width: 9px;height: 9px;border-radius: 50%;margin:0 6px;"
              :style="{ background: switchzhufu == 1 ? 'green' : '#D9D9D9' }"></div>
            <div>订货单位</div>
          </div>
        </div>
        <div class="unitStyleBottom unitWidth" @click="switchs = 1" v-if="switchs == 2">
          <span style="margin-right: 10px;">+</span> 添加单位
        </div>
        <div class="unitStyle unitWidth " style="margin-top: 20px;" v-else>
          <div>副单位</div>
          <div><input style="width: 70px;height: 28px;;border: 1px solid #dddfe6;" type="text"
              v-model="unitItem.conUnitTwo" @input="conUnitTwoinput">
          </div>
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <div style="width: 9px;height: 9px;border-radius: 50%;margin:0 6px;"
              :style="{ background: switchzhufu == 2 ? 'green' : '#D9D9D9' }" @click="switchzhufu = 2"></div>
            <div @click="switchzhufu = 2">订货单位</div>
            <input type="text" disabled placeholder="1">
            <div>{{ unitItem.conUnitTwo }}=</div>
            <input v-model="unitItem.conUnitTwoConvert" style="width: 80px;" type="number">
            {{ unitItem.conUnit }}
            <span style="color: red;margin-left: 8px;cursor: pointer;" @click="deleteEvent">删除</span>
          </div>
        </div>
        <div style="display: flex; justify-content: center;margin-top: 20px;">
          <el-button @click="dialogtitleunit = false">取 消</el-button>
          <el-button type="primary" @click="submitUnit()">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog title="选择类型" :visible.sync="typedialogshow">
      <div class="head-container">
        <el-input v-model="querytypedialogshowquery.conTypeName" size="small" clearable placeholder="请输入耗材类型名称"
          style="width: 100%" class="filter-item" @keyup.enter.native="getTableDatatype" />
        <el-input v-model="querytypedialogshowquery.conTypeCode" size="small" clearable placeholder="请输入耗材类型代码"
          style="width: 100%" class="filter-item" @keyup.enter.native="getTableDatatype" />
        <el-select v-model="querytypedialogshowquery.status" placeholder="请选择商品规格" style="width: 100%">
          <el-option :label="item.label" :value="item.value" v-for="item in typeEnums" :key="item.label" />
        </el-select>
        <div style="margin-top: 10px">
          <el-button type="primary" @click="getTableDatatype">查询</el-button>
          <el-button @click="resetHandletype">重置</el-button>
        </div>
      </div>
      <el-table ref="table" :data="tableDatatype.data" v-loading="tableDatatype.loading" row-key="id">
        <el-table-column label="耗材类型名称" prop="conTypeName" />
        <el-table-column label="耗材类型代码" prop="conTypeCode" />
        <el-table-column label="店铺ID" prop="shopId" />
        <el-table-column label="状态" prop="status">
          <template v-slot="scope">
            <el-tag type="primary" v-if="scope.row.status == '1'">正常</el-tag>
            <el-tag type="danger" v-if="scope.row.status == '0'">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="" width="200">
          <template v-slot="scope">
            <el-button @click="tableDatatypetable(scope.row)">确定</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="head-container">
        <el-pagination :total="tableDatatype.total" :current-page="tableDatatype.page + 1"
          :page-size="tableDatatype.size" layout="total, sizes, prev, pager, next, jumper"
          @current-change="paginationChangetype" />
      </div>
    </el-dialog>
    <el-dialog title="耗材信息" :visible.sync="clickseetypedialogshow">
      <div class="head-container">
        <el-table ref="table" :data="clickseetableData.data" v-loading="clickseetableData.loading" row-key="id"
          height="450">
          <el-table-column label="耗材名称" prop="conName" />
          <el-table-column label="变动库存" prop="amount">
            <template v-slot="scope">
              <span :class="{ red: scope.row.bizType == '-' }">{{ scope.row.bizType }}{{ scope.row.amount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="现有库存" prop="balance" />
          <!-- <el-table-column label="业务编码" prop="bizCode" /> -->
          <el-table-column label="业务说明" prop="bizName" />
          <!-- <el-table-column label="正负号标识" prop="bizType" /> -->
          <!-- <el-table-column label="耗材id" prop="consId" /> -->
          <el-table-column label="商品信息" prop="productName"></el-table-column>
          <el-table-column label="创建时间" prop="createTime"></el-table-column>
          <!-- <el-table-column label="更新时间" prop="updateTime">
          <template v-slot="scope">
            {{ dayjs(scope.row.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column> -->
        </el-table>
      </div>
      <div class="head-container">
        <el-pagination :total="clickseetableData.total" :current-page="clickseetableData.page + 1"
          :page-size="clickseetableData.size" layout="total, sizes, prev, pager, next, jumper"
          @current-change="paginationChangetype" @size-change="(e) => {
            clickseetableData.size = e;
            clickseetableData.page = 0;
            getConsRecord();
          }
            " />
      </div>
    </el-dialog>

    <!-- 耗材盘点 -->
    <AddConsTakin ref="AddConsTakin" @success="resetHandle" />
    <!-- 查看详情 -->
    <cons-record-detail ref="recodeDetail"></cons-record-detail>
    <!-- 导入耗材 -->
    <el-dialog title="导入库存" :visible.sync="dialogVisible">
      <UploadExcel :beforeUpload="excelSuccessUpload" />
    </el-dialog>
  </div>
</template>

<script>
import Sortable from "sortablejs";
import dayjs from "dayjs";
import settings from "@/settings";

function returnPromise(index, prosise) {
  return new Promise((resolve, reject) => {
    prosise.then(res => {
      console.log(res);
      resolve({ sucees: true })
    }).catch(err => {
      console.log(err);
      resolve({ sucees: false })
    })
  })
}
import {
  gettbConsType,
  gettbConsInfo,
  posttbConsInfo,
  posttbConsInfostockIn,
  postapitbConsInfo,
  tbConsInfoFlowcount,
  tbConsInfoFlowstock
} from "@/api/consumable";
import AddConsTakin from "../components/addConsTakin";
import { tbConsInfodownload, tbConsInfoinputStock, unittbConsInfo } from '@/api/invoicing'
import { downloadFile } from "@/utils";
import UploadExcel from '@/components/UploadExcel'
import consRecordDetail from "../components/cons_record_detail";
import { hasPermission } from '@/utils/limits.js'

export default {
  components: { AddConsTakin, UploadExcel, consRecordDetail },
  name: 'information',
  data() {
    return {
      tongji: {},//统计
      dayjs,
      // 切换主副单位
      switchzhufu: "1",
      query: {
        conTypeId: "",
        conTypeName: "",
        conCode: "",
        conName: "",
        status: '',
        createdAt: [],
        sort: 'createTime,desc'
      },
      resetQuery: '',
      libraryshow: false, //耗材入库显示
      libraryshowdata: {
        id: "",
        stockNumber: ""
      },
      ruleslibrary: {
        stockNumber: [
          { required: true, message: "请输入入库数量", trigger: "blur" }
        ]
      },
      categorys: [],
      typeEnums: [
        {
          label: "正常",
          value: "1"
        },
        {
          label: "禁用",
          value: "0"
        }
      ],
      dialogshow: false, //弹框显示
      dialogtitle: "", //文字显示
      typedialogshow: false,
      tableData: {
        data: [],
        page: 0,
        size: 30,
        loading: false,
        total: 0
      },
      querytypedialogshowquery: {
        conTypeCode: "",
        conTypeName: "",
        status: ""
      },
      tableDatatype: {
        data: [],
        page: 0,
        size: 100,
        loading: false,
        total: 0
      },

      clickseetypedialogshow: false,
      clickseetableData: {
        data: [],
        page: 0,
        size: 30,
        loading: false,
        total: 0
      },
      variabilityshow: false,
      variabilitytitle: '',
      stockData: {
        data: [],
        page: 0,
        size: 10,
        loading: false,
        total: 0
      },
      ruleFormLoading: false,
      dialogtitleunit: false,
      unitItem: {},
      switchs: 2,
      ruleForms: [],
      ruleForm: {
        conCode: "",
        conName: "",
        conTypeId: "",
        price: "0",
        conNames: "",
        // surplusStock: '',
        conUnit: "",
        conWarning: "999",
        shopId: localStorage.getItem("shopId"),
        status: ''
      },
      rules: {
        conCode: [
          { required: true, message: "请输入耗材信息代码", trigger: "blur" }
        ],
        conName: [
          { required: true, message: "请输入耗材信息名称", trigger: "blur" }
        ],
        conTypeId: [
          { required: true, message: "请选择耗材类型", trigger: "change" }
        ],
        price: [{ required: true, message: "请输入耗材价格", trigger: "blur" }],
        conWarning: [
          { required: true, message: "请输入耗材预警值", trigger: "blur" }
        ],
        conTypeId: [
          { required: true, message: "请输入耗材类型id", trigger: "blur" }
        ],
        conUnit: [{ required: true, message: "请输入单位", trigger: "blur" }],
        conWarning: [
          {
            required: true,
            message: "请输入单位",
            trigger: "blur"
          }
        ]
      },
      downloadLoading: false,
      uploadLoading: false,
      dialogVisible: false,
      consRecordItem: '',
    };
  },
  mounted() {
    this.resetQuery = { ...this.query }
    this.resetRuleForms()
    this.getTableData();
    this.getTableDatatype();
  },
  methods: {
    deleteEvent() {
      this.switchs = 2
      this.unitItem.conUnitTwo = ''
      this.unitItem.conUnitTwoConvert = ''
    },
    async routerGo(name) {
      let text;
      if (name == 'operation_in') { text = "允许耗材入库" }
      if (name == 'operation_out') { text = "允许耗材出库" }
      let res = await hasPermission(text);
      if (!res) { return; }
      this.$router.push({ name: name })
    },
    closeande() {

    },
    lookDetail(row) {
      this.$refs.recodeDetail.open({
        "consId": row.consId,
        "conName": row.conName
      })
    },
    //解决selectc值改变后未验证问题
    selectChange($event, ref, type) {
      this.$refs[ref][0].validateField(type)
    },
    //重置添加耗材表单
    resetRuleForms() {
      this.ruleForms = [{ ...this.ruleForm }]
      this.$refs['refruleForm0'] && this.$refs['refruleForm0'][0].resetFields()
    },
    //添加耗材弹窗删除
    ruleFormsReduce(index) {
      if (this.ruleForms.length > 1) {
        this.ruleForms.splice(index, 1)
      } else {
        this.$message({ type: "error", message: "至少保留一种耗材" });
      }
    },
    toGoods(productId) {

      this.$router.push({
        path: '/product/product',
        query: {
          productId: productId
        }
      })
    },
    async submitUnit() {

      console.log(this.switchzhufu, '体哦啊是1')

      const res = await unittbConsInfo([{
        defaultUnit: this.switchzhufu == 1 ? this.unitItem.conUnit : this.unitItem.conUnitTwo,
        conUnitTwoConvert: this.unitItem.conUnitTwoConvert * 1,
        conUnitTwo: this.unitItem.conUnitTwo,
        id: this.unitItem.id
      }])
      this.unitItem = {}
      this.dialogtitleunit = false
      this.resetRuleForms()
      this.getTableData();
      this.getTableDatatype();
    },
    //跳转订单列表
    toGoodslist(orderNo) {
      this.$router.push({
        path: '/order_manage/order_list',
        query: {
          orderNo: orderNo
        }
      })
    },
    //添加耗材弹窗增加
    ruleFormsAdd() {
      console.log('add')
      this.ruleForms.push({ ...this.ruleForm })
    },
    // 导入耗材
    async excelSuccessUpload(file) {
      try {
        this.uploadLoading = true
        this.dialogVisible = false
        await tbConsInfoinputStock(file)
        this.uploadLoading = false
        this.$notify.success('导入成功')
        this.resetHandle()
      } catch (error) {
        this.dialogVisible = false
        this.uploadLoading = false
        console.log(error);
      }
    },
    async conNameClick(row) {
      await postapitbConsInfo([{
        id: row.consId,
        ...row,
        shopId: localStorage.getItem('shopId')
      }])
      row.editNYD = 0
      this.$message.success('修改成功')
    },
    async changeswitchstatus(row) {
      await postapitbConsInfo([{
        id: row.consId,
        ...row,
        shopId: localStorage.getItem('shopId')
      }])
      this.$message.success('修改成功')
    },
    computedClass(num) {
      if (num > 0) {
        return 'green'
      } else {
        return 'red'
      }
    },
    conUnitTwoinput(d) {
      // console.log(d.target.value,'调试1')
      this.unitItem.conUnitTwo = d.target.value
    },
    // 状态切换
    async showChange(e, row) {
      await postapitbConsInfo([{
        id: row.id,
        "isCheck": row.isCheck,
        shopId: localStorage.getItem('shopId')
      }])
      this.$message.success('修改成功')
    },
    // 耗材导出
    async protHandle() {
      try {
        this.downloadLoading = true;
        const file = await tbConsInfodownload(this.query)
        downloadFile(file, "耗材", "xlsx");
        this.downloadLoading = false;
      } catch (error) {
        this.downloadLoading = false;
        console.log(error);
      }
    },
    // 单位编辑
    editorHandles(row) {
      // this.unitItem = row;
      this.unitItem.conUnitTwoConvert = row.conUnitTwoConvert
      this.unitItem.id = row.id
      this.unitItem.conUnit = row.conUnit
      this.unitItem.conName = row.conName
      this.unitItem.conUnitTwo = row.conUnitTwo
      if (row.conUnitTwo) this.switchs = 1
      else this.switchs = 2

      // this.switchs = 2
      // if (row. ) {
      //   this.switchs = 1
      // }
      this.dialogtitleunit = true;
    },

    // 编辑
    editorHandle(row) {
      this.dialogtitle = "编辑";
      for (let key in this.ruleForm) {
        this.ruleForm[key] = row[key];
      }
      this.ruleForm.id = row.id;
      this.dialogshow = true;
    },
    // 重置查询
    resetHandle() {
      this.query = { ...this.resetQuery }
      this.query.sort = 'createTime,desc'
      this.query.createdAt = []
      this.tableData.page = 0;
      this.getTableData();
    },
    // 分页回调
    paginationChange(e) {
      this.tableData.page = e - 1;
      this.getTableData();
    },
    paginationChangetype(e) {
      this.clickseetableData.page = e - 1;
      this.getConsRecord();
    },
    // 获取信息
    async getTableData() {
      this.tableData.loading = true;
      let arr = []
      if (this.query.createdAt.length) {
        arr = [this.query.createdAt[0] + ' 00:00:00', this.query.createdAt[1] + ' 23:59:59']
      } else {
        arr = []
      }
      try {
        const res = await gettbConsInfo({
          ...this.query,
          page: this.tableData.page,
          size: this.tableData.size,
          shopId: localStorage.getItem("shopId"),
          createTime: arr
        });
        this.tableData.loading = false;
        this.tableData.total = res.totalElements;
        this.tableData.data = res.content;
        this.gettbConsInfoFlowcount()//统计
        console.log(this.tableData.data)
        // this.tableData.data = res.content.map(v => {
        //   const productIds = v.productId ? v.productId.split(',') : []
        //   return {
        //     ...v,
        //     editNYD: 0,
        //     product: productIds.map((str, index) => {
        //       const startIndex = str.indexOf('_')
        //       const productId = str.slice(0, startIndex)
        //       const productName = str.slice(startIndex + 1, str.length)
        //       return {
        //         productId,
        //         productName: productName + `${(index == productIds.length - 1) ? '' : ','}`
        //       }
        //     })
        //   }
        // });
        console.log(this.tableData.data)
      } catch (error) {
        console.log(error);
      }
    },
    // 
    async gettbConsInfoFlowcount() {
      let arr = []
      if (this.query.createdAt.length) {
        arr = [this.query.createdAt[0] + ' 00:00:00', this.query.createdAt[1] + ' 23:59:59']
      } else {
        arr = []
      }
      try {
        const res = await tbConsInfoFlowcount({
          ...this.query,
          page: this.tableData.page,
          size: this.tableData.size,
          shopId: localStorage.getItem("shopId"),
          startTime: arr[0],
          endTime: arr[1]
        });
        this.tongji = res;
      } catch (error) {
        console.log(error);
      }
    },
    // 列
    async gettbConsInfoFlowstock() {
      this.variabilityshow = true
      switch (this.stockData.column) {
        case 'stockNumber':
          this.variabilitytitle = '现有数量'
          break;
        case 'addCountNumber':
          this.variabilitytitle = '增加数量'
          break;
        case 'addNumber':
          this.variabilitytitle = '手动增加'
          break;
        case 'stockInNumber':
          this.variabilitytitle = '入库'
          break;
        case 'refundNumber':
          this.variabilitytitle = '退货'
          break;
        case 'subCountNumber':
          this.variabilitytitle = '减少数量'
          break;
        case 'subNumber':
          this.variabilitytitle = '手动减少'
          break;
        case 'saleNumber':
          this.variabilitytitle = '消耗'
          break;
        case 'lossNumber':
          this.variabilitytitle = '报损'
          break;
        case 'stockOutNumber':
          this.variabilitytitle = '出库'
          break;
      }
      this.stockData.loading = true;
      let arr = []
      if (this.query.createdAt.length) {
        arr = [this.query.createdAt[0] + ' 00:00:00', this.query.createdAt[1] + ' 23:59:59']
      } else {
        arr = []
      }
      let res = await tbConsInfoFlowstock({
        page: this.stockData.page,
        size: this.stockData.size,
        shopId: localStorage.getItem("shopId"),
        productId: '',//预留耗材id
        column: this.stockData.column,//列名
        conName: this.query.conName,
        createdAt: arr//耗材id
      })
      this.stockData.loading = false;
      this.stockData.data = res.content;
      this.stockData.total = res.totalElements;
    },
    // 分页回调
    wstockChange(e) {
      this.stockData.page = e - 1;
      this.gettbConsInfoFlowstock();
    },
    // 获取类型
    async getTableDatatype() {
      this.tableDatatype.loading = true;
      try {
        const res = await gettbConsType({
          page: this.tableDatatype.page,
          size: this.tableDatatype.size,
          conTypeCode: this.querytypedialogshowquery.conTypeCode,
          conTypeName: this.querytypedialogshowquery.conTypeName,
          status: this.querytypedialogshowquery.status,
          shopId: localStorage.getItem("shopId")
        });
        this.tableDatatype.loading = false;
        this.tableDatatype.data = res.content;
        this.tableDatatype.total = res.totalElements;
      } catch (error) {
        console.log(error);
      }
    },
    // 重置查询
    resetHandletype() {
      this.querytypedialogshowquery.conTypeName = "";
      this.querytypedialogshowquery.conTypeCode = "";
      this.querytypedialogshowquery.status = "";
      this.tableData.page = 0;
      this.getTableDatatype();
    },
    // 选择的类型
    tableDatatypetable(item) {
      // this.ruleForm.conCode = item.conTypeCode
      this.ruleForm.conNames = item.conTypeName;
      this.ruleForm.conTypeId = item.id;
      this.typedialogshow = false;
    },
    async clickdialogfadd(item) {
      this.libraryshow = true;
      this.libraryshowdata.id = item.id;
    },
    async clickdialoglibraryshow(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          await posttbConsInfostockIn({
            id: this.libraryshowdata.id,
            stockNumber: this.libraryshowdata.stockNumber
          });
          this.libraryshow = false;
          this.$refs[formName].resetFields();
          this.getTableData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 弹框修改值  添加  编辑
    clickdialogframe(type, item) {
      if (type == "add") {
        // 添加
        this.dialogtitle = "添加";
        this.getTableDatatype()
        this.$nextTick(() => {
          this.$refs.refruleForm.resetFields();
          this.resetRuleForms()
        });
      } else {
        this.dialogtitle = "编辑";
        this.ruleForm.id = item.consId;
        this.ruleForm.conTypeId = item.conTypeId;
        this.ruleForm.conCode = item.conCode;
        this.ruleForm.conName = item.conName;
        // this.ruleForm.surplusStock = item.surplusStock
        this.ruleForm.conWarning = item.conWarning;
        this.ruleForm.conUnit = item.conUnit;
      }
      this.dialogshow = true;
    },
    //添加
    async submitForms() {
      let isAllPassForm = 0
      for (let i in this.ruleForms) {
        const res = await returnPromise(i, this.$refs['refruleForm' + i][0].validate())
        console.log(res)
        isAllPassForm += res.sucees ? 1 : 0
      }
      //判断验证是否通过
      if (isAllPassForm === this.ruleForms.length) {
        await posttbConsInfo(this.ruleForms)
        this.$message({ type: "success", message: "添加成功" });

        // for(let i of this.ruleForms){
        //   const res=await posttbConsInfo(i)
        //   this.$message({ type: "success", message: "添加成功" });
        // }
        this.dialogshow = false;
        this.resetRuleForms()
        this.ruleFormLoading = false;
        this.getTableData();
      }
    },
    //编辑
    submitForm(formName) {

      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.ruleFormLoading = true;
          if (this.dialogtitle == "编辑") {
            console.log(this.ruleForm, '调试 ')
            await postapitbConsInfo([this.ruleForm]);
            this.$message({ type: "success", message: "编辑成功" });
            this.dialogshow = false;
          } else {
            // //添加
            // console.log(this.ruleForm, '调试')
            // for(let i of this.ruleForms){
            //   console.log(i)
            //   await posttbConsInfo({
            //     ...i
            //    });
            //    this.$message({ type: "success", message: "添加成功" });

            // }

          }
          this.dialogshow = false;
          this.$refs[formName].resetFields();
          this.ruleFormLoading = false;
          this.getTableData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 删除商品
    async delTableHandle(ids) {
      try {
        await tbProductDelete(ids);
        this.getTableData();
      } catch (error) {
        console.log(error);
      }
    },
    // 显示耗材记录
    async clicksee(item) {
      console.log(item, '耗材记录')
      this.consRecordItem = item
      this.clickseetypedialogshow = true;
      this.getConsRecord()
    },
    // 获取耗材记录
    async getConsRecord() {
      try {
        this.clickseetableData.loading = true;
        const res = await gettbConsInfo({
          page: this.clickseetableData.page,
          size: this.clickseetableData.size,
          // consId: this.consRecordItem.consId,
          // conName: this.consRecordItem.conName,
          shopId: localStorage.getItem("shopId"),
          sort: 'createTime,desc'
        });
        this.clickseetableData.loading = false;
        this.clickseetableData.data = res.content;
        this.clickseetableData.total = res.totalElements;
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.goodslang {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .goods-list {
    overflow: hidden; //超出的文本隐藏
    text-overflow: ellipsis; //溢出用省略号显示
    white-space: nowrap; //溢出不换行
  }

  ::v-deep .goods-list .el-button--text span {
    display: block;
    text-align: left;
  }

  ::v-deep .goods-list .el-button--text {
    white-space: break-spaces;
  }
}

.color-success {
  color: #67c23a;
  cursor: pointer;
  font-weight: 700;
}

.color-danger {
  color: #f56c6c;
  font-weight: 700;
  cursor: pointer;
}

.row_wrap {
  display: flex;
  justify-content: space-between;

  .row {
    display: flex;
    align-items: center;
    gap: 10px;
  }
}

.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;
    }
  }
}

.red {
  color: rgb(219, 32, 32);
}

.box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 90px 20px 90px;

  .boxitem {
    min-width: max-content;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 24px;
    background: rgba(244, 249, 255, 0.5);
    border-radius: 10px;

    .boxitem_s {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;

      .boxitem_ses {
        margin-top: 10px;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        .es {
          border-left: 2px solid #DDDFE6;
          padding: 0 10px;
          display: flex;
          justify-content: flex-start;
          align-items: center;

          .e {
            font-family: Source Han Sans CN, Source Han Sans CN;
            font-weight: 400;
            font-size: 12px;
            color: #666666;
          }

          .s {
            margin-left: 10px;
            font-family: Source Han Sans CN, Source Han Sans CN;
            font-weight: 500;
            font-size: 15px;
            color: #3F9EFF;
          }
        }

        .es:nth-child(1) {
          margin-top: 0;
          border-left: none;
        }
      }

      .boxitem_ses:nth-child(1) {
        margin-top: 0;
      }
    }
  }
}

.unitStyle {
  display: flex;
  align-items: center;
  border-radius: 2px 2px 2px 2px;

  >div:first-child {
    width: 95px;
    height: 42px;
    line-height: 42px;
    text-align: center;
    border-right: 1px solid #DDDFE6;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 14px;
    color: #999999;
  }

  >div:nth-child(2) {
    width: 80px;
    height: 42px;
    line-height: 42px;
    text-align: center;
    border-right: 1px solid #DDDFE6;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 14px;
    color: #3F9EFF;
  }

  >div:last-child {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 14px;
    color: #999999;

    >input {
      width: 75px;
      height: 28px;
      background: #FFFFFF;
      border-radius: 2px 2px 2px 2px;
      border: 1px solid #DDDFE6;
      margin: 0 16px;
    }

  }
}

.unitStyleBottom {
  margin-top: 30px;
  line-height: 42px;
  text-align: center;
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 400;
  font-size: 14px;
  color: #3F9EFF;


}

.unitWidth {
  // width: 418px;
  height: 42px;
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #DDDFE6;
}
</style>
