<template>
  <div>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
              @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 align="center" :label="getLabelName" width="200" prop="goods">
        <div class="item" slot-scope="scope">
          <ProjectChoose v-if="itemType === 'project'" @input-blur="save(scope.row)" class="item__input"
                         @selected="getPart" :select-width="'15rem'"/>
          <PartChoose v-if="itemType === 'part'" @input-blur="save(scope.row)" class="item__input" @selected="getPart"
                      :select-width="'15rem'"/>
          <OtherChoose v-if="itemType === 'other'" @input-blur="save(scope.row)" class="item__input" @selected="getPart"
                       :select-width="'15rem'"/>
          <span class="item__txt">{{ scope.row.name ? scope.row.name : scope.row.goods }}</span>
        </div>
      </el-table-column>
      <el-table-column align="center" label="规格" width="180" prop="model"/>
      <el-table-column align="center" label="编码" width="180" prop="code"/>
      <el-table-column align="center" label="数量" width="180" prop="count">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.count"/>
          <span class="item__txt">{{ scope.row.count }}</span>
        </div>
      </el-table-column>
      <el-table-column align="center" label="单位" width="180" 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 align="center" label="单价" width="180" prop="price">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.price"/>
          <span class="item__txt">{{ scope.row.price }}</span>
        </div>
      </el-table-column>
      <el-table-column align="center" label="折扣" width="180" prop="discount">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.discount"/>
          <span class="item__txt">{{ scope.row.discount }}</span>
        </div>
      </el-table-column>
      <el-table-column align="center" label="金额" width="180" prop="totalPrice">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.totalPrice"/>
          <span class="item__txt">{{ scope.row.totalPrice }}</span>
        </div>
      </el-table-column>
      <el-table-column align="center" label="施工人员" width="180" prop="repair">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <StaffChoose @input-blur="save(scope.row)" class="item__input" v-model="scope.row.repair"
                       :select-width="'15rem'"/>
          <span class="item__txt">{{ scope.row.repair ? scope.row.repair.name : scope.row.repair }}</span>
        </div>
      </el-table-column>
      <el-table-column align="center" label="销售人员" width="180" prop="sale">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <StaffChoose @input-blur="save(scope.row)" class="item__input" v-model="scope.row.sale"
                       :select-width="'15rem'"/>
          <span class="item__txt">{{ scope.row.sale ? scope.row.sale.name : scope.row.sale }}</span>
        </div>
      </el-table-column>
      <el-table-column align="center" label="类型" width="180" prop="type">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <ServerChoose @input-blur="save(scope.row)" class="item__input" v-model="scope.row.type"/>
          <span class="item__txt">{{ scope.row.type }}</span>
        </div>
      </el-table-column>
      <el-table-column align="center" label="账类" width="180" prop="accountType">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <el-select v-model="scope.row.accountType" class="item__input" @blur="save(scope.row)">
            <el-option v-for="item in getDict(DICT_TYPE.REPAIR_PAY_TYPE)" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
          <dict-tag class="item__txt" :type="DICT_TYPE.REPAIR_PAY_TYPE" v-model="scope.row.accountType"/>
        </div>
      </el-table-column>
      <el-table-column align="center" label="状态" width="180" prop="itemStatus">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.REPAIR_ITEM_STATUS" v-model="scope.row.itemStatus"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" width="180" prop="remark">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.remark"/>
          <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-plus" @click="handleCreateItem"
          >新增
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteItem(scope.$index)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <WaresForm ref="partFormRef" class="noPadding" @success="returnPart"/>
    <RepairProjectForm class="noPadding" ref="projectFormRef" @success="returnProject"/>
    <OtherForm ref="otherFormRef" class="noPadding" @success="returnOther"/>
  </div>
</template>

<script>
import PartChoose from "@/views/repair/Components/PartChoose.vue";
import StaffChoose from "@/views/repair/Components/StaffChoose.vue";
import ServerChoose from "@/views/repair/Components/ServerChoose.vue";
import {DICT_TYPE} from "@/utils/dict";
import WaresForm from "@/views/repair/wares/WaresForm.vue";
import RepairProjectForm from "@/views/repair/project/form/RepairProjectForm.vue";
import ProjectChoose from "@/views/repair/Components/ProjectChoose.vue";
import OtherChoose from "@/views/repair/Components/OtherChoose.vue";
import OtherForm from "@/views/repair/other/OtherForm.vue";

export default {
  name: "TicketItem",
  components: {
    OtherForm,
    OtherChoose, ProjectChoose, RepairProjectForm, WaresForm, ServerChoose, StaffChoose, PartChoose
  },
  props: {
    itemType: {
      type: String,
      default: 'project',
      required: true
    },
    inListData:{
      type:Array,
      default: () => {return []},
      required: false
    }
  },
  data() {
    return {
      loading: false,
      list: [{}],
      // 需要编辑的属性
      editProp: ["goods", 'count', 'price', 'discount', 'repair', 'sale', 'remark', 'type', 'accountType'],
      // 保存进入编辑的cell
      clickCellMap: {},
      selectRepair: {},
      selectSale: {},
      formData: {
        repair: null,
        sale: null,
      }
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$emit("tableData", val)
      },
      deep: true
    },
    inListData(val){
      if (val && val.length > 0){
        // console.log(val)
        // this.list = val.map(item => {
        //   return {
        //     ...item,
        //     count: item?.itemCount,
        //   }
        // })
      }
    }
  },
  computed: {
    // DICT_TYPE() {
    //   return DICT_TYPE
    // },
    getLabelName() {
      switch (this.itemType) {
        case "project":
          return "维修项目";
        case "part":
          return "维修配件";
        case "other":
          return "附加费用";
        default:
          return '';
      }
    }
  },
  methods: {
    getDict(val) {
      return this.getDictDatas(val)
    },
    // 清空数据
    resetTable() {
      this.list = [{}]
    },
    /** 鼠标移入cell */
    handleCellEnter(row, column, cell, event) {
      const property = column.property
      if (row.id && this.editProp.includes(property)) {
        cell.querySelector('.item__txt').classList.add('item__txt--hover')
      }
    },
    /** 鼠标移出cell */
    handleCellLeave(row, column, cell, event) {
      const property = column.property
      if (row.id && 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)) {
        if (!row.id || property !== 'goods') {
          // 保存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) {
      // TODO 有BUG 更新表格
      if (row.id) {
        row.itemStatus = (row.repair && this.itemType === 'project') ? "02" : "01"
        row.totalPrice = row.count * row.price * (row.discount / 10)
      }
      const id = row.id
      // 取消本行所有cell的编辑状态
      this.clickCellMap[id].forEach(cell => {
        this.cancelEditable(cell)
      })
      this.clickCellMap[id] = []
    },
    async getPart(data) {
      const flag = this.list.find(item => item.id === data.id)
      if (flag) {
        try {
          await this.$modal.confirm(`${data.name}已存在，确定要重复添加？`)
        } catch {
          return
        }
      }
      data = {
        ...data,
        count: 1,
        discount: 10,
        remark: null,
        itemStatus: '01',
        totalPrice: data.price,
        accountType: "01"
      }
      switch (this.itemType) {
        case 'project':
          data.itemStatus = "01"
          data.model = data.spec
          break
        case "part":
          data.itemStatus = "08"
          break
        case "other":
          data.itemStatus = "06"
          break
        default:
          break
      }
      data.type = null
      this.list.splice(this.list.length - 1, 0, data)
    },
    handleDeleteItem(index) {
      if (this.list[index].id) {
        this.list.splice(index, 1)
      }
    },
    // TODO 新增
    handleCreateItem() {
      switch (this.itemType) {
        case "project":
          this.$refs.projectFormRef.open(undefined)
          break
        case "part":
          this.$refs.partFormRef.open(undefined)
          break
        case "other":
          this.$refs.otherFormRef.open(undefined)
          break
        default:
          break
      }
    },
    returnProject() {
      // console.log("新增项目回调")
    },
    returnPart() {
      // console.log("新增配件回调")
    },
    returnOther() {

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

::v-deep .noPadding {
  padding: 0;
}
</style>
