<template>
  <div>
    <el-descriptions class="margin-top" :column="4" :size="'medium'" border style="margin-bottom: 1rem">
      <!--      <template slot="extra">-->
      <!--        <el-button v-if="createTicketType" type="success" size="small">新增客户信息</el-button>-->
      <!--        <el-button v-if="createTicketType" type="primary" size="small" :disabled="!selectUser.id">完善更多客户信息</el-button>-->
      <!--        <el-button type="primary" size="small">选择业务</el-button>-->
      <!--      </template>-->
      <el-descriptions-item>
        <template slot="label">
          用户选择
        </template>
        <UserChoose v-model="selectUser"/>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          车辆选择
        </template>
        <CarChoose v-model="selectCar" :cus-name="selectUser.cusName"/>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          手机
        </template>
        <el-input disabled v-model="selectUser.phoneNumber"/>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          车架号
        </template>
        <el-input disabled v-model="selectCar.vin"/>
      </el-descriptions-item>
      <!--      <el-descriptions-item>-->
      <!--        <template slot="label">-->
      <!--          车牌-->
      <!--        </template>-->
      <!--        <el-input disabled v-model="selectCar.licenseNumber"/>-->
      <!--      </el-descriptions-item>-->
      <el-descriptions-item>
        <template slot="label">
          品牌车系
        </template>
        <el-input disabled v-model="selectCar.modelStr"/>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          保险到期
        </template>
        <el-date-picker disabled
                        v-model="selectCar.insuranceExpiryDate"
                        type="date">
        </el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          年检到期
        </template>
        <el-date-picker disabled
                        v-model="selectCar.nextInspectionDate"
                        type="date">
        </el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          进厂时间
        </template>
        <el-date-picker
          v-model="formData.inTime"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          预计完工
        </template>
        <el-date-picker
          v-model="formData.outTime"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          上次里程
        </template>
        <el-input v-model="selectCar.maintenanceMileage"/>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          本次里程
        </template>
        <el-input v-model="selectCar.newMaintenanceMileage"/>
      </el-descriptions-item>
      <!--      <el-descriptions-item :span="3">-->
      <!--        <template slot="label">-->
      <!--          备注-->
      <!--        </template>-->
      <!--        <el-input v-model="formData.remark"/>-->
      <!--      </el-descriptions-item>-->
      <el-descriptions-item>
        <template slot="label">
          服务顾问
        </template>
        <StaffChoose v-model="selectStaff"/>
      </el-descriptions-item>
    </el-descriptions>
    <el-row :gutter="5" style="margin-bottom: 1rem">
      <el-col v-if="createTicketType" :span="4.8">
        <el-button size="small" @click="$refs['repairAdvice'].open()">维修建议</el-button>
      </el-col>
      <el-col v-if="createTicketType" :span="4.8">
        <el-button size="small" @click="$refs['qualityExplain'].open()">质保说明</el-button>
      </el-col>
      <el-col v-if="createTicketType" :span="4.8">
        <el-button size="small" v-if="formData.endCheck.toString() === '1'" @click="formData.endCheck = 0">终检
        </el-button>
        <el-button size="small" v-if="formData.endCheck.toString() === '0'" @click="formData.endCheck = 1">不终检
        </el-button>
      </el-col>
      <el-col v-if="createTicketType" :span="4.8">
        <el-select v-model="formData.partDisposal" size="small">
          <el-option v-for="item in this.getDictDatas(DICT_TYPE.REPAIR_PART_DISPOSAL)" :key="item.value"
                     :label="item.label" :value="item.value"/>
        </el-select>
      </el-col>
      <el-col v-if="createTicketType" :span="4.8">
        <el-select v-model="formData.repairType" size="small">
          <el-option v-for="item in this.getDictDatas(DICT_TYPE.REPAIR_TYPE)" :key="item.value" :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button size="small" v-if="formData.ticketType === '01'" @click="formData.ticketType = '02'">A单</el-button>
        <el-button size="small" v-if="formData.ticketType === '02'" @click="formData.ticketType = '01'">B单</el-button>
      </el-col>
    </el-row>
    <TicketItem item-type="project" :in-list-data="projectList" @tableData="projectData" ref="projectTable"/>
    <TicketItem v-if="createTicketType" :in-list-data="partList" item-type="part" @tableData="partData"
                ref="partTable"/>
    <TicketItem v-if="createTicketType" :in-list-data="otherList" item-type="other" @tableData="otherData"
                ref="otherTable"/>
    <el-row :gutter="createTicketType ? 2 : 3" style="margin-top: 1rem">
      <el-col :span="createTicketType ? 12 : 16">
        <el-descriptions class="margin-top" :column="createTicketType ? 2 : 3" border :size="'medium'"
                         style="margin-bottom: 1rem">
          <!--          <el-descriptions-item>-->
          <!--            <template slot="label">-->
          <!--              工单号-->
          <!--            </template>-->
          <!--           <TicketChoose @selected="getTickets"/>-->
          <!--          </el-descriptions-item>-->
          <el-descriptions-item>
            <template slot="label">
              时间
            </template>
            <el-date-picker
              v-model="formData.ticketTime"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-descriptions-item>
          <el-descriptions-item v-if="!createTicketType">
            <template slot="label">
              备注
            </template>
            <el-input v-model="formData.remark"/>
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col v-if="createTicketType" :span="12">
        <el-descriptions class="margin-top" :column="5" :size="'medium'"
                         style="margin-left: 1rem;margin-top: 1rem">
          <el-descriptions-item label="数量">{{ formData.count }}</el-descriptions-item>
          <el-descriptions-item label="项目">{{ formData.projectPrice }}</el-descriptions-item>
          <el-descriptions-item label="配件">{{ formData.partPrice }}</el-descriptions-item>
          <el-descriptions-item label="附加">{{ formData.otherPrice }}</el-descriptions-item>
          <el-descriptions-item label="合计">{{ formData.totalPrice }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col v-else :span="8" style="margin-top:1rem;display: flex;justify-content: right">
        <el-button type="danger">结算</el-button>
        <el-button type="warning" @click="handlePendingSave">挂单</el-button>
      </el-col>
    </el-row>
    <el-row v-if="createTicketType" :gutter="2">
      <el-col :span="12">
        <el-descriptions border class="margin-top" :column="1" :size="'medium'">
          <el-descriptions-item>
            <template slot="label">
              备注
            </template>
            <el-input v-model="formData.remark"/>
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col :span="12" style="margin-top:1rem;display: flex;justify-content: right">
        <el-button type="success" @click="handleSave">完成</el-button>
        <el-button type="danger" @click="handlePaid">结算</el-button>
        <!--        <el-button type="primary">通知施工</el-button>-->
        <!--        <el-button type="primary">领料</el-button>-->
        <!--        <el-button type="primary">退料</el-button>-->
      </el-col>
    </el-row>

    <RepairAdvice ref="repairAdvice" v-model="formData.repairAdvice"/>
    <QualityExplain ref="qualityExplain" v-model="formData.quality"/>
  </div>
</template>

<script>
import UserChoose from "@/views/repair/Components/UserChoose.vue";
import StaffChoose from "@/views/repair/Components/StaffChoose.vue";
import TicketItem from "@/views/repair/tickets/Components/TicketItem.vue";
import CarChoose from "@/views/repair/Components/CarChoose.vue";
import {createUniqueCodeByHead} from "@/utils/createUniqueCode";
import {createTickets, getTicketsById} from "@/api/repair/tickets/Tickets";
import RepairAdvice from "@/views/repair/tickets/form/RepairAdvice.vue";
import QualityExplain from "@/views/repair/tickets/form/QualityExplain.vue";
import TicketChoose from "@/views/repair/tickets/Components/TicketChoose.vue";

export default {
  name: "UserInfo",
  components: {TicketChoose, QualityExplain, RepairAdvice, CarChoose, TicketItem, StaffChoose, UserChoose},
  props: {
    createTicketType: {
      type: Boolean,
      required: true,
    }
  },
  watch: {
    selectUser(val) {
      if (!val) {
        this.selectUser = {}
      }
    },
    selectCar(val) {
      if (!val) {
        this.selectCar = {}
      }
    }
  },
  data() {
    return {
      formData: {
        endCheck: 1,
        partDisposal: '01',
        repairType: '01',
        ticketNo: null,
        remark: null,
        inTime: Date.now(),
        outTime: null,
        ticketTime: Date.now(),
        projectPrice: 0,
        partPrice: 0,
        otherPrice: 0,
        totalPrice: 0,
        count: 0,
        userId: null,
        userName: null,
        userMobile: null,
        carId: null,
        carNo: null,
        carVin: null,
        carBrandId: null,
        carBrandName: null,
        carBrandType: null,
        adviserId: null,
        adviserName: null,
        payType: null,
        repairAdvice: null,
        quality: {
          qualityMileage: 3000,
          qualityDay: 30
        },
        qualityMileage: null,
        qualityDay: null,
        ticketType: "01",
        itemList: [],
        ticketsStatus: "01",
      },
      selectUser: {},
      selectCar: {},
      selectStaff: {},
      projectList: [],
      partList: [],
      otherList: []
    }
  },
  methods: {
    projectData(data) {
      // 去掉最后一行
      this.projectList = [...data]
      this.projectList.pop()
      // 通知计算
      this.computedData()
    },
    partData(data) {
      // 去掉最后一行
      this.partList = [...data]
      this.partList.pop()
      // 通知计算
      this.computedData()
    },
    otherData(data) {
      // 去掉最后一行
      this.otherList = [...data]
      this.otherList.pop()
      // 通知计算
      this.computedData()
    },
    computedData() {
      const data = this.formData
      this.formData = {
        ...data,
        projectPrice: 0,
        partPrice: 0,
        otherPrice: 0,
        totalPrice: 0,
        count: 0
      }
      // 项目
      if (this.projectList) {
        this.formData.projectPrice = this.computeByItem(this.projectList)
      }
      // 配件
      if (this.partList) {
        this.formData.partPrice = this.computeByItem(this.partList)
      }
      // 其他
      if (this.otherList) {
        this.formData.otherPrice = this.computeByItem(this.otherList)
      }
    },
    computeByItem(item) {
      const count = item.reduce((x, y) => {
        return x + y.count
      }, 0)
      const totalPrice = item.reduce((x, y) => {
        return x + y.totalPrice
      }, 0)
      this.formData.count += parseInt(count)
      this.formData.totalPrice += parseFloat(totalPrice)
      return parseFloat(totalPrice)
    },
    // 登记保存
    async handleSave() {
      this.createInit()
      this.createItemInit()
      try {
        await createTickets(this.formData)
        this.$modal.msgSuccess("新增成功")
        this.init()
      } catch {
      } finally {
        this.formData.ticketNo = null
      }
    },
    // 初始化
    init() {
      this.formData = {
        endCheck: 1,
        partDisposal: '01',
        repairType: '01',
        ticketNo: null,
        remark: null,
        inTime: Date.now(),
        outTime: null,
        ticketTime: Date.now(),
        projectPrice: 0,
        partPrice: 0,
        otherPrice: 0,
        totalPrice: 0,
        count: 0,
        userId: null,
        userName: null,
        userMobile: null,
        carId: null,
        carNo: null,
        carVin: null,
        carBrandId: null,
        carBrandName: null,
        carBrandType: null,
        adviserId: null,
        adviserName: null,
        payType: null,
        repairAdvice: null,
        quality: {
          qualityMileage: 3000,
          qualityDay: 30
        },
        qualityMileage: null,
        qualityDay: null,
        ticketType: null,
        itemList: [],
        ticketStatus: "01"
      }
      this.selectUser = {}
      this.selectCar = {}
      this.selectStaff = {}
      this.projectList = []
      this.partList = []
      this.otherList = []
      this.resetTable()
    },
    resetTable() {
      this.$refs['projectTable'].resetTable()
      this.$refs['partTable'].resetTable()
      this.$refs['otherTable'].resetTable()
    },
    // 新增基础信息init
    createInit() {
      // 生成工单号
      this.formData.ticketNo = this.formData.ticketNo || createUniqueCodeByHead("GD")
      // 质保说明
      this.formData.qualityMileage = this.formData.quality.qualityMileage
      this.formData.qualityDay = this.formData.quality.qualityDay
      // 选择的用户
      this.formData.userId = this.selectUser?.id
      this.formData.userName = this.selectUser?.cusName
      this.formData.userMobile = this.selectUser?.phoneNumber

      // 选择的车辆
      this.formData.carId = this.selectCar?.id
      this.formData.carNo = this.selectCar?.licenseNumber
      this.formData.carVin = this.selectCar?.vin
      this.formData.carBrandId = this.selectCar?.carBrand
      this.formData.carBrandName = this.selectCar?.brandStr
      this.formData.carBrandType = this.selectCar?.brandType

      // 服务顾问
      this.formData.adviserId = this.selectStaff?.id
      this.formData.adviserName = this.selectStaff?.name
    },
    // 新增子表信息init
    createItemInit() {
      // 项目
      this.formData.itemList = [...this.formData.itemList, ...this.formatItem("project", this.projectList)]
      // 配件
      this.formData.itemList = [...this.formData.itemList, ...this.formatItem("part", this.partList)]
      // 其他
      this.formData.itemList = [...this.formData.itemList, ...this.formatItem("other", this.otherList)]
    },
    // 子表信息预处理
    formatItem(type, list) {
      if (!(list && list.length > 0)) {
        return []
      }
      return list.map(item => {
        const temp = {
          ...item,
          itemName: item.name,
          itemCount: item?.count,
          itemUnit: item.unit,
          itemPrice: item.price,
          itemDiscount: item.discount,
          itemMoney: item.totalPrice,
          repairId: item?.repair?.id,
          repairName: item?.repair?.name,
          saleId: item?.sale?.id,
          saleName: item?.sale?.name,
          itemTypeId: item?.type?.id,
          remark: item.remark,
          itemStatus: item.itemStatus,
          id: null
        }
        switch (type) {
          case 'project':
            temp['itemType'] = "01"
            break;
          case 'part':
            temp['itemType'] = "02"
            break;
          case 'other':
            temp['itemType'] = "03"
            break;
          default:
            return "";
        }
        temp[type + 'Id'] = item.id
        return temp;
      })
    },
    // 查看工单
    async getTickets(id) {
      try {
        const res = await getTicketsById(id)
        const data = res.data
        this.formData = {
          ...data,
          quality: {qualityMileage: data.qualityMileage, qualityDay: data.qualityDay}
        }
        const itemList = this.formData.itemList
        this.selectUser = {id: data.userId}
        this.selectCar = {id: data.carId}
        this.projectList = [itemList.find(item => item.itemType === '01')]
        this.partList = [itemList.find(item => item.itemType === '02')]
        this.otherList = [itemList.find(item => item.itemType === '03')]
      } catch {
      }
    },
    // 挂单
    handlePendingSave() {
      this.formData.ticketsStatus = "06"
      this.handleSave()
    },
    // 结算
    handlePaid() {
      this.formData.ticketsStatus = '02'
      this.handleSave()
    }
  }
}
</script>

<style scoped lang="scss">
</style>
