<template>
  <div>
    <!-- 搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="关键字" prop="query">
        <el-input style="width: 20rem" type="text" placeholder="工单号、车牌号、联系电话" v-model="queryParams.query"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="序号" align="center" width="80">
        <template scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据号" align="center" prop="no" />
      <el-table-column label="服务顾问" align="center" prop="adviserName" />
      <el-table-column label="申请人" align="center" prop="repairName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.TICKET_WARES_STATUS" v-model="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleDispose(scope.row)" icon="el-icon-edit">
            处理
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <el-dialog title="单据处理" :visible.sync="dialogVisible" width="80%" v-dialogDrag append-to-body>
      <el-table el-table v-loading="dialogLoading" :data="items" :stripe="true" :show-overflow-tooltip="true" :row-class-name="getClass" @selection-change="handleSelect">
        <el-table-column type="selection" width="80" align="center" />
        <el-table-column label="名称" align="center" prop="waresName" :show-overflow-tooltip="true"/>
        <el-table-column label="规格" align="center" prop="wares.model" width="180"/>
        <el-table-column label="申请数量" align="center" prop="waresCount" width="180"/>
        <el-table-column label="库存数量" align="center" prop="wares.stock" width="180"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePass(false)" :disabled="selections.length === 0 || selections.filter(item => !item.isStock).length !== 0">通过选择</el-button>
        <el-button type="success" @click="handlePass(true)"
                   :disabled="this.items.filter(item => !item.isStock).length !== 0"
                   :title="this.items.filter(item => !item.isStock).length !== 0 ? '有配件库存不足':''">通过全部</el-button>
        <el-button v-if="type" type="primary" @click="handleCreate(false)" :disabled="selections.length === 0">选择生成采购单</el-button>
        <el-button v-if="type" type="primary" @click="handleCreate(true)">全部生成采购单</el-button>
      </div>
    </el-dialog>

    <el-dialog title="采购单" :visible.sync="inStockDialog" width="80%" v-dialogDrag append-to-body>
      <el-table
                :data="partList"
                :stripe="true"
                :show-overflow-tooltip="true"
                show-summary
                :summary-method="getSummaries"
                @cell-mouse-enter="handleCellEnter"
                @cell-mouse-leave="handleCellLeave"
                @cell-click="handleCellClick"
      >
        <el-table-column label="序号" align="center">
          <template scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="name" width="200"/>
        <el-table-column label="规格" align="center" width="180" prop="model"/>
        <el-table-column label="商品编码" align="center" width="180" prop="code">
          <div class="item" slot-scope="scope">
            <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.code"
                      placeholder="请输入内容"></el-input>
            <span class="item__txt">{{ scope.row.code }}</span>
          </div>
        </el-table-column>
        <el-table-column label="仓库" align="center" width="150" prop="warehouse">
          <div class="item" slot-scope="scope">
            <WarehouseChoose @input-blur="save(scope.row)" class="item__input" v-model="scope.row.ware"
                             @change="changeWare(scope.row)"/>
            <span class="item__txt">{{ scope.row.warehouseName }}</span>
          </div>
        </el-table-column>
        <el-table-column label="库存" align="center" width="150" prop="stock"/>
        <el-table-column label="单位" align="center" width="150" prop="unit">
          <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.REPAIR_UNIT" v-model="scope.row.unit"/>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" width="150" prop="count">
          <div class="item" slot-scope="scope">
            <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.count"
                      placeholder="请输入内容"></el-input>
            <span class="item__txt">{{ scope.row.count }}</span>
          </div>
        </el-table-column>
        <el-table-column label="上次进价" align="center" width="150" prop="purPrice"/>
        <el-table-column label="采购单价" align="center" width="150" prop="newPrice">
          <div class="item" slot-scope="scope">
            <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.newPrice"
                      placeholder="请输入内容"></el-input>
            <span class="item__txt">{{ scope.row.newPrice }}</span>
          </div>
        </el-table-column>
        <el-table-column label="采购金额" align="center" width="150" prop="totalPrice"/>
        <el-table-column label="备注" align="center" width="180" prop="remark">
          <div class="item" slot-scope="scope">
            <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.remark"
                      placeholder="请输入内容"></el-input>
            <span class="item__txt">{{ scope.row.remark }}</span>
          </div>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="150">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteItem(scope.$index)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="1" style="margin-top: 1rem">
        <el-col :span="24">
          <el-input v-model="remark" placeholder="备注"/>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="handleSubmit">结算</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getPage, pass, passBackTicketWares} from "@/api/repair/tickets/TicketWares";
import {listTwItem} from "@/api/repair/tickets/TWItem";
import {createUniqueCodeByHead} from "@/utils/createUniqueCode";
import {parseTime} from "@/utils/ruoyi";
import SoTable from "@/views/repair/stockOperate/Components/SoTable.vue";
import WarehouseChoose from "@/views/repair/Components/WarehouseChoose.vue";
import {createRepairSo} from "@/api/repair/stockOperate/stockOperate";
import {getUserProfile} from "@/api/system/user";

export default {
  name: "WaresItem",
  components: {WarehouseChoose, SoTable},
  props:{
    type: Boolean,
  },
  data(){
    return{
      queryParams:{
        pageNo: 1,
        pageSize: 10,
        query: null,
        type: this.type ? "01" : "02"
      },
      showSearch: true,
      loading: false,
      list:[],
      total: 0,
      dialogVisible: false,
      items:[],
      dialogLoading: false,
      selections:[],
      formData:{},
      inStockDialog: false,
      partList: [],
      includeColumn: ['count', 'totalPrice'],
      // 保存进入编辑的cell
      clickCellMap: {},
      // 需要编辑的属性
      editProp: ['warehouse', 'count', 'newPrice', 'remark', 'code'],
      remark: null,
    }
  },
  mounted() {
    this.getList()
  },
  methods:{
    // 通过 true是全部、false是选择
    async handlePass(flag){
      // 生成领料单
      if (this.type){
        this.formData.repairSo = {
          soType: "02",
          soNo: createUniqueCodeByHead("LL"),
          userId: this.formData.repairId,
          userName: this.formData.repairName,
          soTime: parseTime(Date.now(), '{y}-{m}-{d}'),
          soStatus: "04",
          purchaseType: "01"
        }
        if (flag){
          this.formData.repairSois = [...this.items.map(item => {
            return {
              soiType: '02',
              goodsId: item.waresId,
              goodsCount: item.waresCount,
            }
          })]
          this.formData.items = [...this.items.map(item => {
            return {
              id: item.id,
              waresStatus: "04"
            }
          })]
        }else {
          this.formData.repairSois = [...this.selections.map(item => {
            return {
              soiType: '02',
              goodsId: item.waresId,
              goodsCount: item.waresCount,
            }
          })]
          this.formData.items = [...this.selections.map(item => {
            return {
              id: item.id,
              waresStatus: "04"
            }
          })]
        }
        try {
          await pass(this.formData)
          this.$modal.msgSuccess("处理成功")
          await this.getList()
        }finally {
          this.dialogVisible = false
        }
      }else {
        // 退料方法
        this.formData = {}
        if (flag){
          this.formData.items = [...this.items.map(item => {
            return {
              id: item.id,
              waresStatus: "05"
            }
          })]
        }else {
          this.formData.items = [...this.selections.map(item => {
            return {
              id: item.id,
              waresStatus: "05"
            }
          })]
        }
        try {
          await passBackTicketWares(this.formData)
          this.$modal.msgSuccess("处理成功")
          await this.getList()
        }finally {
          this.dialogVisible = false
        }
      }
    },
    // 生成采购 true是全部、false是选择
    async handleCreate(flag){
      this.inStockDialog = true
      if (flag){
        this.partList = [...this.items.map(item => {
          return {
            ...item.wares,
            count: item.waresCount,
            newPrice: item.wares.purPrice,
            totalPrice: item.waresCount * item.wares.purPrice
          }
        })]
      }else {
        this.partList =  [...this.selections.map(item => {
          return {
            ...item.wares,
            count: item.waresCount,
            newPrice: item.wares.price,
            totalPrice: item.waresCount * item.wares.price
          }
        })]
      }
      this.dialogVisible = false
    },
    async getList(){
      try {
        this.loading = true
        const res = await getPage(this.queryParams)
        if (res.data){
          this.list = res.data.records
          this.total = res.data.total
        }
      }finally {
        this.loading = false
      }
    },
    handleQuery(){
      this.queryParams.pageNo = 1
      this.getList()
    },
    resetQuery(){
      this.resetForm('queryForm')
      this.handleQuery()
    },
    async handleDispose(row){
      this.formData = {}
      this.formData = {
        ...row
      }
      this.dialogVisible = true
      try {
        this.dialogLoading = true
        const data = {twId: row.id}
        const res = await listTwItem(data)
        this.items = res.data
        // 库存判断
        this.items.forEach(item => {
          item.isStock = item.waresCount <= item.wares.stock
        })
        // 只要未领料的
        if (this.type){
          this.items = this.items.filter(item => item.waresStatus === '02')
        }else {
          // 未领料的不要
          this.items = this.items.filter(item => item.waresStatus !== '02')
        }
      }finally {
        this.dialogLoading = false
      }
    },
    getClass(row){
      if (this.type && !row.row.isStock){
        return 'stock'
      }
      return ''
    },
    handleSelect(row){
      this.selections = row
    },
    // 设置不统计的字段
    getSummaries(param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (this.includeColumn.includes(column.property)) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        }
      });
      return sums
    },
    /** 鼠标移入cell */
    handleCellEnter(row, column, cell, event) {
      const property = column.property
      if (this.editProp.includes(property)) {
        cell.querySelector('.item__txt').classList.add('item__txt--hover')
      }
    },
    /** 鼠标移出cell */
    handleCellLeave(row, column, cell, event) {
      const property = column.property
      if (this.editProp.includes(property)) {
        cell.querySelector('.item__txt').classList.remove('item__txt--hover')
      }
    },
    /** 点击cell */
    handleCellClick(row, column, cell, event) {
      const property = column.property
      if (this.editProp.includes(property)) {
        // 保存cell
        this.saveCellClick(row, cell)
        cell.querySelector('.item__txt').style.display = 'none'
        cell.querySelector('.item__input').style.display = 'inline'
        cell.querySelector('input').focus()
      }
    },
    /** 取消编辑状态 */
    cancelEditable(cell) {
      cell.querySelector('.item__txt').style.display = 'inline'
      cell.querySelector('.item__input').style.display = 'none'
    },
    /** 保存进入编辑的cell */
    saveCellClick(row, cell) {
      const id = row.id
      if (this.clickCellMap[id] !== undefined) {
        if (!this.clickCellMap[id].includes(cell)) {
          this.clickCellMap[id].push(cell)
        }
      } else {
        this.clickCellMap[id] = [cell]
      }
    },
    /** 保存数据 */
    save(row) {
      // 更新表格的数据
      row.totalPrice = row.count * row.newPrice
      const id = row.id
      // 取消本行所有cell的编辑状态
      this.clickCellMap[id].forEach(cell => {
        this.cancelEditable(cell)
      })
      this.clickCellMap[id] = []
    },
    changeWare(row) {
      if (row.ware) {
        row['wareId'] = row.ware.id
        row['warehouse'] = row.ware.id
        row['warehouseName'] = row.ware.name
      }
    },
    // 通知父组件，删除数据
    deleteItem(index) {
      this.partList.splice(index, 1)
    },
    // 提交
    async handleSubmit(){
      try {
        await this.createInit()
        await createRepairSo(this.formData)
        this.inStockDialog = false
        this.$modal.msgSuccess("新增成功")
        await this.getList()
      }catch{
      }
    },
    // 提交前的构建
    async createInit(){
      const res = await getUserProfile()
      this.formData = {}
      this.formData = {
        soType: '01',
        purchaseType: '01',
        soNo: createUniqueCodeByHead("CG"),
        userId: res.data.id,
        userName: res.data.nickname,
        soTime: parseTime(Date.now(), '{y}-{m}-{d}'),
        itemCount: this.partList.length,
        totalPrice: this.partList.reduce((x, y) => {return x + y.totalPrice}, 0),
        soStatus: "03",
        remark: this.remark,
      }
      this.formData.goodsList = [...this.partList.map(item => {
        return {
          soiType: '01',
          goodsId: item.id,
          goodsType: '0',
          wareId: item?.wareId,
          goodsCount: item.count,
          goodsPrice: item.newPrice,
          remark: item.remark
        }
      })]
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-table .stock td{
  background-color: #ff0000 !important; /* 红色背景 */
}
.item {
  .item__input {
    display: none;
    width: 100px;
    /* 调整elementUI中样式 如果不需要调整请忽略 */
    .el-input__inner {
      height: 24px !important;
    }

    /* 调整elementUI中样式 如果不需要调整请忽略 */
    .el-input__suffix {
      i {
        font-size: 12px !important;
        line-height: 26px !important;
      }
    }
  }

  .item__txt {
    box-sizing: border-box;
    border: 1px solid transparent;
    width: 100px;
    line-height: 24px;
    padding: 0 8px;
  }

  .item__txt--hover {
    border: 1px solid #dddddd;
    border-radius: 4px;
    cursor: text;
  }
}
</style>
