<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <div class="tab-header webtop">
        <div>{{ viewTitle }}</div>
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate()">保存</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="toService()">转维修单</el-button>
          <el-button type="danger" size="small" :disabled="submitdisabled" @click="toCancellation()">作废</el-button>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <div class="listconadd">
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
          <el-row style="border-top: 1px solid #e0e3eb">
            <el-col :span="8">
              <div class="span-sty">制单人</div>
              <el-form-item><span class="addinputInfo">{{ formobj.createByName }}</span></el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">制单部门</div>
              <el-form-item><span class="addinputInfo">{{ formobj.deptName }}</span></el-form-item>
            </el-col>
            <el-col :span="10">
              <div class="span-sty">制单日期</div>
              <el-form-item><span class="addinputInfo">{{ formobj.createTime }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>预约服务顾问</div>
              <el-form-item>
                <el-select class="addinputInfo" v-model="formobj.waitorName" placeholder="请选择" @change="waitorChange" clearable filterable>
                  <el-option v-for="item in user_list" :key="item.sid" :label="item.name" :value="item.name"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">预约设备</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.reserveEquip" clearable placeholder="" /></el-form-item>
            </el-col>
            <el-col :span="10">
              <div class="span-sty"><span class="icon">*</span>预约时间</div>
              <el-form-item>
                <div class="addinputInfo">
                  <el-date-picker v-model="formobj.reserveStart" :picker-options="pickerStartData(formobj.reserveEnd)" style="width: 200px" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期" />
                  <span style="padding: 0 4px">至</span>
                  <el-date-picker v-model="formobj.reserveEnd" :picker-options="pickerEndData(formobj.reserveStart)" style="width: 200px" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>科目</div>
              <el-form-item prop="subject">
                <el-select class="addinputInfo" v-model="formobj.subject" :disabled="formobj.sitemVos.length > 0" placeholder="请选择" @change="changeSubject" clearable filterable>
                  <el-option v-for="item in subject_list" :key="item.subjectSid" :label="item.subject" :value="item.subject"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <div class="span-sty">备注</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.remarks" clearable placeholder="" /></el-form-item>
            </el-col>
          </el-row>
          <div class="title">客户信息</div>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">客户</div>
              <el-form-item>
                <div style="display: flex;flex-direction: row;justify-content: space-between;align-items: center">
                  <div>
                    <span class="addinputInfo">{{ formobj.customerName }}</span>
                  </div>
                  <el-button type="primary" size="mini" @click="selectCustomer()">选择</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="span-sty">联系电话</div>
              <el-form-item><span class="addinputInfo">{{ formobj.mobile }}</span></el-form-item>
            </el-col>
            <el-col :span="10">
              <div class="span-sty">车牌号/车架号</div>
              <el-form-item><span class="addinputInfo">{{ formobj.vehMark }}/{{ formobj.vinNo }}</span></el-form-item>
            </el-col>
          </el-row>
          <div class="title titleOne">
            <div>维修项目</div>
            <el-button type="primary" size="mini" class="btntopblueline" @click="serviceAdd">添加</el-button>
          </div>
          <el-table :key="serviceKey" :data="formobj.sitemVos" :index="index" border style="width: 100%">
            <el-table-column fixed width="60" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column fixed label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="serviceDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="维修项目" align="center" width="300">
              <template slot-scope="scope">
                <el-popover placement="right" width="600" trigger="click">
                  <div>
                    <el-table :data="serviceData" v-loading="serviceLoading" highlight-current-row @current-change="serviceCurrentChange($event, scope.row)">
                      <el-table-column fixed prop="sitemName" label="项目名称" align="center" />
                      <el-table-column prop="sitemCode" label="项目编码" align="center" />
                      <el-table-column prop="hourPrice" label="工时单价" align="center" />
                      <el-table-column prop="hours" label="工时数" align="center" />
                      <el-table-column prop="price" label="销售价" align="center" />
                    </el-table>
                    <pagination v-show="serviceData.length > 0" :total="serviceQuery.total" :page.sync="serviceQuery.current" :limit.sync="serviceQuery.size" class="pagination" @pagination="serviceInput(scope.row.serviceItem)"/>
                  </div>
                  <el-input slot="reference" v-model="scope.row.serviceItem" @input="serviceInput(scope.row.serviceItem)" clearable placeholder="项目名称、拼音"/>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="hourPrice" label="工时单价" align="center" width="150" />
            <el-table-column prop="hours" label="工时数" align="center" width="150" />
            <el-table-column prop="price" label="销售价" align="center" width="150" />
            <el-table-column label="备注" align="center" min-width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" clearable placeholder="" />
              </template>
            </el-table-column>
          </el-table>
          <div v-show="formobj.sid !== ''">
            <div class="title">跟踪记录</div>
            <el-row style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center;">
              <el-col :span="24">
                <el-button type="primary" size="small" @click="handleClick('已联系,车主会如约来店')">已联系,车主会如约来店</el-button>
                <el-button type="primary" size="small" @click="handleClick('已联系,电话未接听')">已联系,电话未接听</el-button>
                <el-button type="primary" size="small" @click="handleClick('已联系,无效预约')">已联系,无效预约</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item><el-input v-model="formobj.trackLog" type="textarea" :autosize="{ minRows: 2, maxRows: 6}" clearable placeholder="" /></el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-button type="primary" size="small" @click="handleAdd">添加跟踪记录</el-button>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
    </div>
    <!-- 选择客户 -->
    <selectCustomer v-show="viewState == 2" ref="divCus" @backData="backData" @doback="resetState"/>
  </div>
</template>

<script>
import req from '@/api/operation/preregistration'
import Pagination from '@/components/pagination'
import { selAllByOrgSidPath, selSubjectInfo, getServiceItemListPage } from '@/api/Common/dictcommons'
import selectCustomer from '@/components/publicPage/selectCustomer'

export default {
  name: 'PreregistrationAdd',
  components: {
    Pagination,
    selectCustomer
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      index: 0,
      user_list: [],
      subject_list: [],
      // service服务
      serviceKey: 1,
      serviceLoading: false,
      serviceQuery: {
        current: 1,
        size: 5,
        total: 0,
        params: {
          sitemName: '',
          useOrgSid: '',
          subject: ''
        }
      },
      serviceData: [],
      formobj: {
        sid: '',
        createBySid: '',
        remarks: '',
        createByName: '',
        billNo: '',
        reserveStart: '',
        reserveEnd: '',
        waitorSid: '',
        waitorName: '',
        reserveEquip: '',
        customerVehicleSid: '',
        customerSid: '',
        customerName: '',
        mobile: '',
        vehMark: '',
        vehModel: '',
        sitemVos: [],
        orgPath: '',
        createTime: '',
        vinNo: '',
        trackLog: '',
        trackLogs: [],
        deptSid: '',
        deptName: '',
        customerOrg: '',
        userSid: '',
        subjectSid: '',
        subject: ''
      },
      rules: {
        subject: [{ required: true, message: '科目不能为空', trigger: 'change' }]
      }
    }
  },
  methods: {
    // 限制开始日期只可选择今天之后的
    pickerStartData(newtime) {
      return {
        disabledDate(time) {
          if (newtime !== '') {
            return time.getTime() < Date.now() - 8.64e7 || time.getTime() > new Date(newtime)
          } else {
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },
    // 限制截止日期只可选择开始日期之后的
    pickerEndData(newtime) {
      return {
        disabledDate(time) {
          return time.getTime() < new Date(newtime) || time.getTime() < Date.now() - 8.64e7
        }
      }
    },
    init() {
      selAllByOrgSidPath({ orgSidPath: window.sessionStorage.getItem('defaultOrgPath') }).then((resp) => {
        if (resp.success) {
          this.user_list = resp.data
        }
      })
      selSubjectInfo({ useOrgSid: window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1) }).then((resp) => {
        if (resp.success) {
          this.subject_list = resp.data
        }
      })
    },
    showAdd() {
      this.viewTitle = '【新增】预约单'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      this.formobj.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      this.formobj.createByName = window.sessionStorage.getItem('name')
      this.formobj.createBySid = window.sessionStorage.getItem('userSid')
      this.formobj.userSid = window.sessionStorage.getItem('userSid')
      this.formobj.deptName = window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1)
      this.formobj.deptSid = window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1)
      var nowDate = new Date()
      var date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        day: nowDate.getDate()
      }
      this.formobj.createTime = date.year + '-' + (date.month >= 10 ? date.month : '0' + date.month) + '-' + (date.day >= 10 ? date.day : '0' + date.day)
    },
    showEdit(sid) {
      this.viewTitle = '【编辑】预约单'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      req.fetchBySid(sid).then((res) => {
        if (res.success) {
          this.formobj = res.data
          this.formobj.userSid = window.sessionStorage.getItem('userSid')
        }
      })
    },
    getNumber(val, limit) {
      val = val.replace(/[^0-9.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    selectCustomer() {
      this.viewState = 2
      this.$refs['divCus'].showData(this.formobj.deptSid, '')
    },
    backData(value) {
      this.viewState = 1
      value = JSON.parse(JSON.stringify(value))
      this.formobj.customerName = value.customerName
      this.formobj.customerSid = value.sid
      this.formobj.customerVehicleSid = value.customerVehicleSid
      this.formobj.mobile = value.mobile
      this.formobj.vehMark = value.vehMark
      this.formobj.vinNo = value.vinNo
    },
    waitorChange(value) {
      const choose = this.user_list.filter((item) => item.name === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.waitorSid = choose[0].sid
      } else {
        this.formobj.waitorSid = ''
      }
    },
    changeSubject(value) {
      const choose = this.subject_list.filter((item) => item.subject === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.subjectSid = choose[0].subjectSid
      } else {
        this.formobj.subjectSid = ''
      }
    },
    serviceAdd() {
      if (this.formobj.subject === '')  {
        this.$message({ showClose: true, type: 'error', message: '请先选择科目' })
        return
      }
      this.formobj.sitemVos.push({
        serviceItemSid: '',
        serviceItem: '',
        hourPrice: '',
        hours: '',
        price: '',
        remarks: ''
      })
    },
    serviceInput(value) {
      if (this.formobj.subjectSid === '') {
        this.$message({ showClose: true, type: 'error', message: '请先选择科目' })
        return
      }
      this.serviceQuery.params.useOrgSid = this.formobj.deptSid
      this.serviceQuery.params.sitemName = value
      this.serviceQuery.params.subject = this.formobj.subject
      this.serviceLoading = true
      getServiceItemListPage(this.serviceQuery).then((response) => {
        if (response.success) {
          this.serviceLoading = false
          this.serviceData = response.data.records
          this.serviceQuery.total = response.data.total
        } else {
          this.serviceLoading = false
          this.serviceData = []
          this.serviceQuery.total = 0
        }
      })
    },
    serviceDelete(index) {
      this.formobj.sitemVos.splice(index, 1)
    },
    serviceCurrentChange(value, row) {
      row.serviceItemSid = value.sid
      row.serviceItem = value.sitemName
      row.hourPrice = value.hourPrice
      row.hours = value.hours
      row.price = value.price
      row.remarks = value.remarks
      document.body.click()
    },
    // 计算销售价=工时数*工时单价
    computeXSJ(row) {
      row.price = Math.round((parseFloat(row.hourPrice === '' ? '0' : row.hourPrice) * parseFloat(row.hours === '' ? '0' : row.hours)) * 100) / 100
    },
    // 计算工时数=销售价除以工时单价
    computeGSS(row) {
      row.hours = Math.round((parseFloat(row.price === '' ? '0' : row.price) / parseFloat(row.hourPrice === '' ? '0' : row.hourPrice)) * 100) / 100
    },
    handleClick(value) {
      this.formobj.trackLog = value
    },
    handleAdd() {
      if (this.formobj.trackLog !== '') {
        req.saveTrackingRecord(this.formobj).then((res) => {
          if (res.success) {
            this.$message({ showClose: true, type: 'success', message: '添加成功' })
          }
        })
      } else {
        this.$message({ showClose: true, type: 'error', message: '跟踪记录不能为空' })
      }
    },
    saveOrUpdate() {
      if (this.formobj.waitorName === '') {
        this.$message({ showClose: true, type: 'error', message: '预约服务顾问不能为空' })
        return
      }
      if (this.formobj.reserveStart === '' || this.formobj.reserveEnd === '' || this.formobj.reserveStart === null || this.formobj.reserveEnd === null) {
        this.$message({ showClose: true, type: 'error', message: '预约时间不能为空' })
        return
      }
      if (this.formobj.customerName === '') {
        this.$message({ showClose: true, type: 'error', message: '客户信息不能为空' })
        return
      }
      if (this.formobj.sitemVos.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '维修项目列表不能为空' })
        return
      }
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.saveOrUpdate(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    toService() {
      if (this.formobj.waitorName === '') {
        this.$message({ showClose: true, type: 'error', message: '预约服务顾问不能为空' })
        return
      }
      if (this.formobj.reserveStart === '' || this.formobj.reserveEnd === '') {
        this.$message({ showClose: true, type: 'error', message: '预约时间不能为空' })
        return
      }
      if (this.formobj.customerName === '') {
        this.$message({ showClose: true, type: 'error', message: '客户信息不能为空' })
        return
      }
      if (this.formobj.sitemVos.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '维修项目列表不能为空' })
        return
      }
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.convertedRepairOrders(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    toCancellation() {
      const tip = '请确认是否作废该预约单'
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        req.invalid({ sid: this.formobj.sid }).then((res) => {
          if (res.success) {
            loading.close()
            this.$message({ showClose: true, type: 'success', message: '作废成功' })
            this.handleReturn('true')
          }
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {
      })
    },
    resetState() {
      this.viewState = 1
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        createBySid: '',
        remarks: '',
        createByName: '',
        billNo: '',
        reserveStart: '',
        reserveEnd: '',
        waitorSid: '',
        waitorName: '',
        reserveEquip: '',
        customerVehicleSid: '',
        customerSid: '',
        customerName: '',
        mobile: '',
        vehMark: '',
        vehModel: '',
        sitemVos: [],
        orgPath: '',
        createTime: '',
        vinNo: '',
        trackLog: '',
        trackLogs: [],
        deptSid: '',
        deptName: '',
        customerOrg: '',
        userSid: '',
        subjectSid: '',
        subject: ''
      }
      this.submitdisabled = false
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.span-sty {
  width: 130px !important;
}
.addinputInfo {
  margin-left: 120px !important;
}
.formaddcopy02 .el-row .el-col /deep/ .el-form-item .addinputw {
  margin-left: 120px !important;
  width: calc(100% - 115px);
}
.titleOne{
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>
