<template>
  <el-table v-loading="loading"
            :data="list"
            :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"/>
    <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="soByType ? '上次进价' : '成本'" align="center" width="150" prop="price"/>
    <el-table-column v-if="soByType" 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="soByType ? '采购金额' : '合计'" 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>
</template>

<script>
import WarehouseChoose from "@/views/repair/Components/WarehouseChoose.vue";

export default {
  name: "SoTable",
  components: {WarehouseChoose},
  props: {
    soByType: {
      type: Boolean,
      defaultValue: true,
      required: true
    },
    partList: {
      type: Array,
      defaultValue: false,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      list: [],
      includeColumn: ['count', 'totalPrice'],
      // 需要编辑的属性
      editProp: this.soByType ? ['warehouse', 'count', 'newPrice', 'remark'] : ['count', 'remark'],
      // 保存进入编辑的cell
      clickCellMap: {}
    }
  },
  watch: {
    partList(val) {
      if (val && val.length > 0) {
        const data = val[val.length - 1]
        const newData = {
          ...data,
          count: 1,
          totalPrice: data.price * 1,
          remark: '',
          newPrice: data.price,
        }
        this.list.push(newData)
      }else {
        this.list = []
      }
    },
    list: {
      handler(newVal, oldVal) {
        this.$emit("tableData", newVal)
      },
      deep: true
    }
  },
  methods: {
    // 通知父组件，删除数据
    deleteItem(index) {
      this.$emit("deleteItem", index)
    },
    // 设置不统计的字段
    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
      }
    }
  }
}
</script>

<style scoped lang="scss">
.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>
