<template>
  <div class="app-container">
    <el-dialog title="申请单查看" :visible.sync="dialogVisible" width="80%" v-dialogDrag append-to-body>
      <el-card class="box-card">
        <!-- 卡片头 -->
        <div slot="header" class="clearfix">
          <i class="el-icon-plus"/>
          <span>工单信息</span>
        </div>
        <!-- 卡片内容 -->
        <div>
          <el-descriptions class="margin-top" :column="4" :size="'medium'" border style="margin-bottom: 1rem">
            <el-descriptions-item>
              <template slot="label">
                订单编号
              </template>
              {{ info.ticketNo }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                维修类别
              </template>
              <dict-tag :type="DICT_TYPE.REPAIR_TYPE" v-model="info.repairType"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                状态
              </template>
              <dict-tag :type="DICT_TYPE.REPAIR_TICKETS_WORK_STATUS" v-model="info.ticketsWorkStatus"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                客户名称
              </template>
              {{ info.userName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                车牌号
              </template>
              {{ info.carNo }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                车系
              </template>
              {{ info.carBrandName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                手机号
              </template>
              {{ info.userMobile }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                创建时间
              </template>
              {{ parseTime(info.createTime, '{y}-{m}-{d}') }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                预计完工
              </template>
              {{ parseTime(info.outTime, '{y}-{m}-{d}') }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                合计金额
              </template>
              {{ info.totalPrice }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                参考成本
              </template>
              {{ info.cost }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                参考毛利
              </template>
              {{ info.profit }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                领料状态
              </template>
              <dict-tag :type="DICT_TYPE.REPAIR_PART_STATUS" v-model="info.partStatus"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                服务顾问
              </template>
              {{ info.adviserName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                所属门店
              </template>
              {{ info.corpId }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                工单状态
              </template>
              <dict-tag :type="DICT_TYPE.REPAIR_TICKETS_STATUS" v-model="info.ticketsStatus"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                备注
              </template>
              {{ info.remark }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>
      <el-card class="box-card">
        <!-- 卡片头 -->
        <div slot="header" class="clearfix">
          <i class="el-icon-plus"/>
          <span>配件信息</span>
        </div>
        <!-- 卡片内容 -->
        <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 label="状态" prop="waresStatus">
              <el-select v-model="queryParams.waresStatus">
                <el-option v-for="item in this.getDictDatas(DICT_TYPE.TW_ITEM_STATUS)" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </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="items" :stripe="true" :show-overflow-tooltip="true"
                    @cell-mouse-enter="handleCellEnter"
                    @cell-mouse-leave="handleCellLeave"
                    @cell-click="handleCellClick"
          >
            <el-table-column label="序号" align="center" width="80">
              <template scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
<!--            <el-table-column align="center" label="客户可见" prop="isShow" v-if="userRole === 'service_advisor' && type" width="180">-->
<!--              <template slot-scope="scope">-->
<!--                <el-switch-->
<!--                  v-model="scope.row.isShow"-->
<!--                  active-text="是"-->
<!--                  inactive-text="否"-->
<!--                  active-value="1"-->
<!--                  inactive-value="0"-->
<!--                  @change="changeIsShow(scope.row)"-->
<!--                >-->
<!--                </el-switch>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <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 v-if="userRole === 'service_advisor' && type" label="折扣" align="center" prop="itemDiscount" width="180">
<!--              <div v-if="formData.status === '01'"  class="item" slot-scope="scope">-->
<!--&lt;!&ndash;                <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.itemDiscount"/>&ndash;&gt;-->
<!--                <DiscountInput @input-blur="save(scope.row)" class="item__input" v-model="scope.row.itemDiscount" />-->
<!--                <span class="item__txt">{{ scope.row.itemDiscount === 1 ? "无折扣" : scope.row.itemDiscount }}</span>-->
<!--              </div>-->
              <div slot-scope="scope">
                <span>{{ scope.row.itemDiscount === 1 ? "无折扣" : scope.row.itemDiscount }}</span>
              </div>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="waresStatus" width="180">
              <template slot-scope="scope">
                <dict-tag :type="DICT_TYPE.TW_ITEM_STATUS" :value="scope.row.waresStatus" />
              </template>
            </el-table-column>
            <el-table-column  align="center" label="备注" prop="remark" width="180" :show-overflow-tooltip="true"/>
          </el-table>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer" v-if="info.status === '01' && (userRole === 'service_advisor' || userRole === 'general_inspection')">
        <el-button type="primary" @click="handleAudit(true)">通 过</el-button>
        <el-button @click="handleAudit(false)">驳 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getTicketsById} from "@/api/repair/tickets/Tickets";
import {auditTicketWares} from "@/api/repair/tickets/TicketWares";
import {listTwItem, updateIsShow} from "@/api/repair/tickets/TWItem";
import DiscountInput from "@/views/repair/tickets/Components/DiscountInput.vue";

export default {
  name: "TicketWaresShow",
  components: {DiscountInput},
  props:{
    userRole: String,
    type: Boolean
  },
  data(){
    return{
      info:{},
      items:[],
      dialogVisible: false,
      queryParams: {
        twId: null,
        query: null,
        waresStatus: null
      },
      showSearch: true,
      loading: false,
      formData: {},
      clickCellMap: {},
      editProp: [],
    }
  },
  methods:{
    async open(row){
      if (row){
        this.formData = row
        const res = await getTicketsById(row.ticketId)
        this.info = res.data
        this.info.status = row.status
        this.queryParams.twId = row.id
        await this.getTwItem()
      }
      this.dialogVisible = true
    },
    async getTwItem(){
      try {
        this.loading = true
        const res = await listTwItem(this.queryParams)
        this.items = res.data
        this.items = [...this.items.map(item => {
          return {
            ...item,
            itemDiscount: 1,
          }
        })]
      }finally {
        this.loading = false
      }
    },
    handleQuery(){
      this.getTwItem()
    },
    resetQuery(){
      this.resetForm('queryForm')
      this.handleQuery()
    },
    async changeIsShow(row){
      try {
        this.loading = true
        await updateIsShow({id: row.id, isShow: row.isShow})
        await this.getTwItem()
      }finally {
        this.loading = false
      }
    },
    // 审核
    async handleAudit(flag){
      try {
        this.formData['status'] = flag ? "02" : '05'
        // 处理配件信息
        this.formData.wares = [...this.items.map(item => {
          return {
            itemName: item.waresName,
            itemCount: item.waresCount,
            itemUnit: item.wares.unit,
            itemPrice: item.wares.price,
            repairIds: this.formData.repairId,
            repairNames: this.formData.repairName,
            saleId: this.formData.adviserId,
            saleName: this.formData.adviserName,
            itemDiscount: item.itemDiscount,
            itemMoney: item.wares.price * item.waresCount * (item.itemDiscount / 10),
            partId: item.waresId,
            remark: item.remark
          }
        })]
        await auditTicketWares(this.formData)
        this.dialogVisible = false
        this.$modal.msgSuccess("审核成功")
        this.$emit('success')
      }catch {

      }

    },
    /** 鼠标移入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) {
      if (row.itemDiscount <= 0 || row.itemDiscount > 10){
        row.itemDiscount = 10
        this.$modal.msgError("折扣只能是1-10")
      }
      const id = row.id
      // 取消本行所有cell的编辑状态
      this.clickCellMap[id].forEach(cell => {
        this.cancelEditable(cell)
      })
      this.clickCellMap[id] = []
    },
  }
}
</script>

<style scoped lang="scss">
.box-card {
  margin-bottom: 10px;
}
.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>
