<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="200" prop="coupon">-->
      <!--        <div class="item" slot-scope="scope">-->
      <!--          <el-select class="item__input" v-model="scope.row.coupon.id" clearable filterable @blur="save(scope.row)">-->
      <!--            <el-option v-for="coupon in couponList" :key="coupon.id" :label="coupon.couponName" :value="coupon.id" />-->
      <!--          </el-select>-->
      <!--          <span class="item__txt">{{ get }}</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 v-if="!exportColumn.includes('price')" 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 v-if="!exportColumn.includes('discount')" 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 v-if="!exportColumn.includes('totalPrice')" 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 v-if="!exportColumn.includes('repair')" align="center" label="施工人员" width="180" prop="repair">
        <div v-if="scope.row.id" class="item" slot-scope="scope">
          <WorkerChoose @input-blur="save(scope.row)" class="item__input" v-model="scope.row.repair"
                        :select-width="'15rem'"/>
          <span class="item__txt">{{ scope.row.repair ? getRepairName(scope.row.repair) : scope.row.repair }}</span>
        </div>
      </el-table-column>
      <el-table-column v-if="!exportColumn.includes('sale')" 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'" :is-get="scope.row.id"/>
          <span class="item__txt">{{ scope.row.sale ? scope.row.sale.name : scope.row.sale }}</span>
        </div>
      </el-table-column>
      <el-table-column  v-if="!exportColumn.includes('type')" 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  v-if="!exportColumn.includes('accountType')" 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  v-if="!exportColumn.includes('itemStatus')" 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" v-if="!exportColumn.includes('addBtn')"
          >新增
          </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";
import request from "@/utils/request";
import {getOtherByName} from "@/api/repair/other";
import {getProjectByName} from "@/api/repair/project";
import {getWaresByName} from "@/api/repair/wares";
import WorkerChoose from "@/views/repair/Components/WorkerChoose.vue";

export default {
  name: "TicketItem",
  components: {
    WorkerChoose,
    OtherForm,
    OtherChoose, ProjectChoose, RepairProjectForm, WaresForm, ServerChoose, StaffChoose, PartChoose
  },
  props: {
    itemType: {
      type: String,
      default: 'project',
      required: true
    },
    inListData: {
      type: Array,
      default: () => {
        return []
      },
      required: false
    },
    couponList: {
      type: Array,
      default: () => {
        return []
      },
      required: false
    },
    // 排除的字段
    exportColumn:{
      type: Array,
      default: () => {return []},
      required: false
    }
  },
  data() {
    return {
      loading: false,
      list: [{
        coupon: {
          id: null
        }
      }],
      // 需要编辑的属性
      editProp: ["goods", 'count', 'price', 'discount', 'repair', 'sale', 'remark', 'type', 'accountType', 'coupon'],
      // 保存进入编辑的cell
      clickCellMap: {},
      selectRepair: {},
      selectSale: {},
      formData: {
        repair: null,
        sale: null,
      }
    }
  },
  watch: {
    list: {
      handler(val) {
        if (val && val.length > 1){
          this.$emit("tableData", val)
          const coupons = val.filter(item => item.coupon).map(item => item.coupon)
          if (coupons && coupons.length > 0) {
            this.$emit("changeCoupon", coupons)
          }
        }
      },
      deep: true
    },
    inListData(val) {
      if (val && val.length > 0) {
        val.forEach(item => {
          item = {
            ...item,
            count: item.itemCount,
            totalPrice: item.itemMoney,
          }
        })
      }else {
        this.list =  [{
          coupon: {
            id: null
          }
        }]
      }
    }
  },
  computed: {
    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) {
      // console.log(row)
      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)
      }
    },
    // 新增
    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
      }
    },
    async returnProject(name) {
      const res = await getProjectByName(name)
      const data = res.data
      if (data) {
        this.list.splice(this.list.length - 1, 0, {
          ...data,
          count: 1,
          totalPrice: data.price,
          type: null
        })
      }
      // this.list.push(row)
    },
    async returnPart(name) {
      const res = await getWaresByName(name)
      const data = res.data
      if (data) {
        this.list.splice(this.list.length - 1, 0, {
          ...data,
          count: 1,
          totalPrice: data.price,
          type: null
        })
      }
      // this.list.push(row)
    },
    async returnOther(name) {
      const res = await getOtherByName(name)
      const data = res.data
      if (data) {
        this.list.splice(this.list.length - 1, 0, {
          ...data,
          count: 1,
          totalPrice: data.price,
          type: null
        })
      }
    },
    getRepairName(data) {
      return data.map(item => item.userName).join(',')
    }
  }
}
</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>
