<template>
  <div>
    <!-- 搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="关键字" prop="ticketNo">
        <el-input style="width: 20rem" type="text" placeholder="工单号、车牌号、联系电话" v-model="queryParams.ticketNo"/>
      </el-form-item>
      <el-form-item label="时间" prop="searchTimeArray">
        <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="queryParams.searchTimeArray"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"/>
      </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">
        <template scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="ticketNo" width="200"/>
      <el-table-column label="维修类别" align="center" prop="repairType" width="180">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.REPAIR_TYPE" v-model="scope.row.repairType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="userName" width="180"/>
      <el-table-column label="车牌号" align="center" prop="carNo" width="180"/>
      <el-table-column label="车系" align="center" prop="carBrandName" width="180"/>
      <el-table-column label="手机号" align="center" prop="userMobile" width="180"/>
      <el-table-column label="操作" fixed="right" align="center" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleShow(scope.row)"
          >查看
          </el-button>
          <el-button v-if="userRole === 'service_advisor' && isFinish" size="mini" type="text" icon="el-icon-refresh" @click="handleEditRecord(scope.row)">
            维修记录设置
          </el-button>
          <el-button
            v-if="(scope.row.ticketsWorkStatus === '01' && userRole === 'repair_staff') && nowUser.id === scope.row.nowRepairId"
            size="mini" type="text" icon="el-icon-check" @click="handleTake(scope.row)">
            接单
          </el-button>
          <el-button v-if="userRole === 'service_advisor' && scope.row.ticketsWorkStatus === '01'" size="mini" type="text" icon="el-icon-check" @click="handleNotify(scope.row)">
            通知施工
          </el-button>
          <el-button size="mini"
                     v-if="scope.row.ticketsWorkStatus !== '01' &&userRole === 'repair_staff'  && !isFinish && nowUser.id === scope.row.nowRepairId"
                     type="text" icon="el-icon-monitor" @click="handleRecord(scope.row, 'kssg')">
            开始施工
          </el-button>
          <el-button size="mini"
                     v-if=" scope.row.ticketsWorkStatus !== '01' && userRole === 'repair_staff' && !isFinish && nowUser.id === scope.row.nowRepairId"
                     type="text" icon="el-icon-monitor" @click="handleRecord(scope.row, 'sgz')">
            过程记录
          </el-button>
          <el-button size="mini"
                     v-if="scope.row.ticketsWorkStatus !== '01' && userRole === 'repair_staff' && !isFinish && nowUser.id === scope.row.nowRepairId"
                     type="text" icon="el-icon-monitor" @click="handleRecord(scope.row, 'sgwczj')">
            施工完成
          </el-button>
<!--          <el-button @click="handleRecord(scope.row, 'zj')" size="mini" type="text" icon="el-icon-monitor" v-if="userRole === 'general_inspection' && scope.row.ticketsWorkStatus === '05'">-->
<!--            终检-->
<!--          </el-button>-->
          <el-button @click="handleReTake(scope.row)" size="mini" type="text" icon="el-icon-refresh"
                     v-if="(userRole === 'repair_staff' ? (leader ? !isFinish : false) : false) && !(scope.row.ticketsWorkStatus !== '01' && userRole === 'repair_staff' && !isFinish)">
            重新指派
          </el-button>
          <el-dropdown
            v-if="scope.row.ticketsWorkStatus !== '01' && ((userRole === 'service_advisor' || userRole === 'general_inspection') && !isFinish)"
            @command="(command) => handleCommand(command, scope.$index, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="!isFinish && scope.row.ticketsWorkStatus !== '01' && userRole === 'repair_staff'" command="handleGet" size="mini" type="text" icon="el-icon-document-add"
              >申请配件
              </el-dropdown-item>
<!--              <el-dropdown-item v-if="scope.row.ticketsWorkStatus !== '01' && userRole === 'repair_staff'" command="handleBack" size="mini" type="text" icon="el-icon-document-delete"-->
<!--              >申请退料-->
<!--              </el-dropdown-item>-->
              <!-- 还要判断是不是员工 -->
              <el-dropdown-item
                v-if="userRole !== 'repair_staff'  && !isFinish && scope.row.ticketsWorkStatus !== '01'"
                command="handleReTake" size="mini" type="text" icon="el-icon-refresh"
              >重新指派
              </el-dropdown-item>
              <el-dropdown-item
                v-if="userRole === 'service_advisor'  && !isFinish && scope.row.ticketsWorkStatus !== '01'"
                command="handleEditRecord" size="mini" type="text" icon="el-icon-refresh"
              >维修记录设置
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="listTickets"
    />
    <TicketsShow ref="ticketsShow" :user-role="userRole"/>
    <UpdateRepair ref="updateRepair" @success="listTickets"/>
    <TWOperate ref="twOperate" @success="listTickets"/>
    <UpdateRecord ref="updateRecord" @success="listTickets" />

    <el-dialog title="退料申请" :visible.sync="backVisible" width="60%" v-dialogDrag append-to-body>
      <el-table v-loading="backLoading" :data="partList" :stripe="true" :show-overflow-tooltip="true"
                @cell-mouse-enter="handleCellEnter"
                @cell-mouse-leave="handleCellLeave"
                @cell-click="handleCellClick"
                @selection-change="rowSelect"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column label="商品名称" prop="itemName" align="center"/>
        <el-table-column label="规格" prop="ware.model" align="center"/>
        <el-table-column label="数量" prop="itemCount" align="center">
          <div v-if="scope.row.id" class="item" slot-scope="scope">
            <el-input @blur="save(scope.row)" class="item__input" v-model="scope.row.itemCount"/>
            <span class="item__txt">{{ scope.row.itemCount }}</span>
          </div>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center">
          <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>
      <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 @click="doBack(false)" type="primary" :disabled="selections.length === 0">退料选择</el-button>
        <el-button @click="doBack(true)" type="success" :disabled="partList.length === 0">退料全部</el-button>
      </div>
    </el-dialog>

    <RecordSetting ref="recordSet" />
  </div>
</template>

<script>
import {getPageType, updateTake, getTicketsById} from "@/api/repair/tickets/Tickets";
import TicketsShow from "@/views/repair/tickets/Components/TicketsShow.vue";
import UpdateRepair from "@/views/repair/tickets/form/UpdateRepair.vue";
import TWOperate from "@/views/repair/tickets/form/TWOperate.vue";
import {createUniqueCodeByHead} from "@/utils/createUniqueCode";
import {updateTicketWares} from "@/api/repair/tickets/TicketWares";
import {getIfLeader} from "@/api/repair/repairworker";
import UpdateRecord from "@/views/repair/tickets/form/UpdateRecord.vue";
import {getUserProfile} from "@/api/system/user";
import RecordSetting from "@/views/repair/tickets/form/RecordSetting.vue";

export default {
  name: "TicketManagerItem",
  components: {RecordSetting, UpdateRecord, TWOperate, UpdateRepair, TicketsShow},
  props: {
    isFinish: {
      type: Boolean,
    },
    userRole: {
      type: String,
      default: '',
      required: true
    },
    isType:{
      type: String,
    }
  },
  data() {
    return {
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        ticketNo: null,
        searchTimeArray: [],
        isFinish: this.isFinish ? "1" : "0",
      },
      showSearch: true,
      loading: false,
      list: [],
      total: 0,
      backVisible: false,
      partList: [],
      backLoading: false,
      // 保存进入编辑的cell
      clickCellMap: {},
      // 需要编辑的属性
      editProp: ['remark', 'itemCount'],
      selections: [],
      formData: {},
      remark: null,
      leader: false,
      nowUser: null,
    }
  },
  mounted() {
    this.listTickets()
    this.isLeader()
    this.getNowUser()
  },
  methods: {
    async getNowUser(){
      const res = await getUserProfile()
      this.nowUser = res.data
    },
    async isLeader(){
        const res = await getIfLeader()
        this.leader = res.data
    },
    async listTickets() {
      try {
        this.loading = true
        const res = await getPageType(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.listTickets()
    },
    // 重置
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 查看
    handleShow(row) {
      this.$refs.ticketsShow.open(row)
    },
    // 配件申请
    handleGet(row) {
      row = {
        ...row,
        type: true
      }
      this.$refs.twOperate.open(row)
    },
    // 接单
    async handleTake(row) {
      try {
        this.loading = true
        await this.$modal.confirm("确认接单吗？")
        await updateTake(row.id)
        this.$modal.msgSuccess("接单成功")
        await this.listTickets()
      }finally {
        this.loading = false
      }
    },
    // 退料
    async handleBack(row){
      this.formData = {}
      this.formData = row
      this.remark = null
      this.backVisible = true
      try {
        this.backLoading = true
        const res = await getTicketsById(row.id)
        this.partList = res.data.wares
      }finally {
        this.backLoading = false
      }
    },
    // 重新指派
    handleReTake(row){
      row = {
        ...row,
        // 还要判断是不是班组长
        isLeads: this.userRole === 'repair_staff'
      }
      this.$refs.updateRepair.open(row)
    },
    // 指派员工，通知施工
    handleNotify(row){
      this.$refs.updateRepair.open(row)
    },
    // 更多操作
    handleCommand(command, index, row){
      switch (command){
        case 'handleReTake':
          this.handleReTake(row)
          break
        case 'handleGet':
          this.handleGet(row)
          break
        case 'handleBack':
          this.handleBack(row)
          break
        case 'handleEditRecord':
          this.handleEditRecord(row)
          break
        default:
          break
      }
    },
    /** 鼠标移入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) {
      // 更新表格的数据
      console.log(row, this.clickCellMap)
      const id = row.id
      // 取消本行所有cell的编辑状态
      this.clickCellMap[id].forEach(cell => {
        this.cancelEditable(cell)
      })
      this.clickCellMap[id] = []
    },
    rowSelect(val){
      this.selections = val
    },
    async doBack(flag){
      const data = {
        no: createUniqueCodeByHead("TLSQ"),
        ticketId: this.formData.id,
        type: "02",
        status: "01",
        remark: this.remark,
        adviserId: this.formData.adviserId,
        adviserName: this.formData.adviserName
      }
      if (flag){
        data.items = this.partList
      }else {
        data.items = this.selections
      }
      await updateTicketWares(data)
      this.backVisible = false
      this.$modal.msgSuccess("申请成功");
      await this.listTickets()
    },
    handleRecord(row, type){
      row = {
        ...row,
        clickType: type
      }
      this.$refs.updateRecord.open(row)
    },
    // 设置维修图片可不可见
    handleEditRecord(row){
      this.$refs.recordSet.open(row.id)
    },
  }
}
</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>
