<template>
  <div class="app-container">
    <div v-show="viewState== 1">
      <!--标题按钮部分开始-->
      <div class="tab-header webtop">
        <!--标题-->
        <div>{{ viewTitle }}</div>
        <!--start 添加修改按钮-->
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate()">保存
          </el-button>
          <el-button type="primary" size="small" @click="submitVehicleApply()">提交
          </el-button>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <!--标题按钮部分结束-->
      <!--Start 新增修改部分-->
      <div class="listconadd">
        <div class="titwu"><span>厂家采购</span></div>
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
          <el-row class="rowStyle">
            <el-col :span="8" class="colOneStyle">
              <div class="span-sty spanOneWidth"><span>分公司:</span></div>
              <el-form-item><span class="addinputInfo addinputOne">{{ formobj.createOrgName }}</span></el-form-item>
            </el-col>
            <el-col :span="8" class="colOneStyle">
              <div class="span-sty spanOneWidth"><span>申请人:</span></div>
              <el-form-item><span class="addinputInfo addinputOne">{{ formobj.createByName }}</span></el-form-item>
            </el-col>
            <el-col :span="8" class="colOneStyle">
              <div class="span-sty spanOneWidth"><span>申请日期:</span></div>
              <el-form-item><span class="addinputInfo addinputOne">{{ formobj.applicationDate }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowStyle">
            <el-col :span="8" class="colStyle">
              <div class="span-sty spanOneWidth"><span>采购类型:</span></div>
              <el-form-item>
                <el-select v-model="formobj.applyType" placeholder="请选择" @change="changeApplyType" clearable class="addinputInfo addinputOne">
                  <el-option v-for="item in applyType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="colStyle">
              <div class="span-sty spanOneWidth"><span>采购原因:</span></div>
              <el-form-item>
                <el-select v-model="formobj.schedulingType" placeholder="请选择" @change="changeSchedulingType" clearable class="addinputInfo addinputOne">
                  <el-option v-for="item in schedulingType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="colStyle">
              <div class="span-sty spanOneWidth"><span>订金付款备注:</span></div>
              <el-form-item><el-input class="addinputw addinputOne" :disabled="formobj.currentAmount === '0' || formobj.currentAmount === ''" v-model="formobj.payRemarks" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowStyle">
            <el-col :span="24" class="colStyle">
              <div class="span-sty spanOneWidth"><span>备注:</span></div>
              <el-form-item><el-input class="addinputw addinputOne" v-model="formobj.remarks" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <div class="title">
            <div>排产车型列表</div>
            <div>
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="addCommodity()">车型选择</el-button>
            </div>
          </div>
          <el-table :key="tableKey" :data="formobj.busVehicleApplyDetailList" :index="index" border style="width: 100%" show-summary :summary-method="getSummaries">
            <el-table-column fixed width="110px" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column fixed label="操作" width="190px" align="center" header-align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="dataDelete(scope.$index)">删除
                </el-button>
                <el-button size="mini" type="primary" @click="handleShangZhuang(scope.$index)">上装选择</el-button>
              </template>
            </el-table-column>
            <el-table-column label="车型" align="center" header-align="center" width="250">
              <template slot-scope="scope">
                <span>{{ scope.row.vehicleName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="常用配置" align="left" header-align="center" width="400">
              <template slot-scope="scope">
                <span>{{ scope.row.configName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="内部编码" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.insideCode }}</span>
              </template>
            </el-table-column>
            <el-table-column label="排产数量" header-align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.quantity" @keyup.native="scope.row.quantity = oninput(scope.row.quantity,2)" placeholder="" class="addinputw" clearable/>
              </template>
            </el-table-column>
            <el-table-column prop="applyForDeposit" label="申请订金" header-align="center" width="150">
              <template slot-scope="scope" prop="applyForDeposit">
                <el-input v-model="scope.row.applyForDeposit" @keyup.native="scope.row.applyForDeposit = oninput(scope.row.applyForDeposit,2)" placeholder="" class="addinputw" clearable/>
              </template>
            </el-table-column>
            <el-table-column label="厂家合同价" header-align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.contractPrice" @keyup.native="scope.row.contractPrice = oninput(scope.row.contractPrice,2)" placeholder="" class="addinputw" clearable/>
              </template>
            </el-table-column>
            <el-table-column label="销售指导价" header-align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.saleGuPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="备注" header-align="center" width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" placeholder="" class="addinputw" clearable/>
              </template>
            </el-table-column>
            <el-table-column label="上装信息" header-align="center" width="180" align="center">
              <template slot-scope="scope">
                <el-button type="primary" v-show="scope.row.busVehicleApplySz !== null && scope.row.busVehicleApplySz !== undefined" size="mini" @click="handleUpdate(scope.row.busVehicleApplySz, scope.$index)">编辑</el-button>
                <el-button type="danger" v-show="scope.row.busVehicleApplySz !== null && scope.row.busVehicleApplySz !== undefined" size="mini" @click="handleDel(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="上装销售指导价" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.guidePrice }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
    <!--End 添加修改部分-->
    <!--选择车型和常用配置-->
    <configuration v-show="viewState == 2" ref="divconfiguration" @backData="backData" @doback="closePage"/>
    <shangzhuangpeizhi v-show="viewState == 3" ref="divShangzhuangpeizhi" @backData="backPeizhi" @doback="closePage"/>
    <shangzhuangpeizhiAdd v-show="viewState == 4" ref="divShangzhuangpeizhiAdd" @backData="backPeizhiAdd" @doback="closePage"/>
  </div>
</template>

<script>
import req from '@/api/supplychain/busvehicleapply'
import configuration from './chexingbyconfiguration'
import shangzhuangpeizhi from '../../../views/supplychain/cheliangpaichan/shangzhuangselect/shangzhuangpeizhi'
import shangzhuangpeizhiAdd from '../../../views/supplychain/cheliangpaichan/shangzhuangselect/shangzhuangpeizhiAdd'
import { getPathSidByUserSid, fetchBySid } from '@/api/cheliang/dictcommons'

export default {
  name: 'cheliangpaichanAdd',
  components: {
    configuration,
    shangzhuangpeizhi,
    shangzhuangpeizhiAdd
  },
  data() {
    return {
      viewTitle: '',
      dialogStatus: '',
      viewState: 1,
      index: 0,
      tableKey: 0,
      // 下拉框
      schedulingType_list: [], // 排产订金使用
      applyType_list: [],
      isRead: false,
      // 表单数据
      formobj: {
        sid: '', // 一条数据的sid
        createByDeptSid: '',
        createBySid: '', // 用户人sid
        createByName: '', // 制单人
        applicationCode: '', // 申请编号
        applicationDate: '', // 申请日期
        applyType: '', // 采购类型
        applyTypeKey: '',
        schedulingType: '', // 采购原因
        schedulingTypeKey: '',
        remarks: '', // 备注
        payRemarks: '',
        currentAmount: '', // 当前订金金额
        salesSid: '', // 销售订单sid 可为空，只有客户订单时才有
        instanceId: '', // 流程实例ID
        taskId: '', // 任务ID
        createOrgSid: '',
        createOrgName: '',
        busVehicleApplyDetailList: []
      },
      rules: {},
      submitdisabled: false
    }
  },
  methods: {
    init() {
      req.pullDown({ type: 'schedulingType' }).then((res) => {
        if (res.success) {
          this.schedulingType_list = res.data
        }
      })
      req.pullDown({ type: 'applyType' }).then((res) => {
        if (res.success) {
          this.applyType_list = res.data
        }
      })
    },
    getUserOrg() {
      getPathSidByUserSid({ userSid: window.sessionStorage.getItem('userSid') }).then((resp) => {
        if (resp.success) {
          this.formobj.createOrgSid = resp.data
          fetchBySid(this.formobj.createOrgSid).then((response) => {
            if (response.success) {
              this.formobj.createOrgName = response.data.name
            }
          })
        }
      })
    },
    newDate() {
      let date = new Date()
      let year = date.getFullYear() // 年
      let month = date.getMonth() + 1 // 月
      let day = date.getDate() // 日
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      this.formobj.applicationDate = year + '-' + month + '-' + day
    },
    oninput(val, limit = 0) {
      val = val.replace(/[^\d]/g, '') // 保留数字
      val = val.replace(/^00/, '0'); // 开头不能有两个0
      /^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
    },
    // 明细表添加一行数据
    addCommodity() {
      this.viewState = 2
      this.$refs['divconfiguration'].showData(this.formobj.busVehicleApplyDetailList)
    },
    // 明细表删除一行数据
    dataDelete(index) {
      this.formobj.busVehicleApplyDetailList.splice(index, 1)
    },
    showAdd() {
      this.init()
      this.getUserOrg()
      this.newDate()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.dialogStatus = 'add'
      this.viewTitle = '【新增】厂家采购'
      this.formobj.createBySid = window.sessionStorage.getItem('userSid')
      this.formobj.createByName = window.sessionStorage.getItem('name')
    },
    showEdit(sid, row) {
      this.init()
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.dialogStatus = 'edit'
      this.viewTitle = '【编辑】厂家采购'
      console.log('编辑回显', sid)
      req.fetchBySid(sid).then((resp) => {
        const data = resp.data
        this.formobj = data
        this.formobj.instanceId = data.procInstId
      }).catch((e) => {
        this.formobj = row
      })
    },
    // 车型常用配置列表--新增确定返回的数据
    backData(value) {
      this.viewState = 1
      console.log('确认返回的车辆数据', value)
      if (value.length > 0) {
        value.forEach((e) => {
          this.formobj.busVehicleApplyDetailList.push({
            quantity: '',
            applySid: '',
            configSid: e.configSid,
            configName: e.configName,
            // useDeposit: '',
            applyForDeposit: '',
            contractPrice: '',
            remarks: '',
            saleGuPrice: e.guidedPrice,
            insideCode: e.insideCode, // 内部编码
            vehicleName: e.vehicleAlias,
            vehicleSid: e.modelSid,
            guidePrice: ''
          })
          if (e.insideCode) {
            this.isRead = true
          } else {
            this.isRead = false
          }
        })
      }
    },
    changeApplyType(value) {
      let bb = null
      this.applyType_list.forEach((e) => {
        if (e.dictValue === value) {
          bb = {
            key: e.dictKey,
            value: e.dictValue
          }
        }
      })
      this.formobj.applyTypeKey = bb.key
    },
    changeSchedulingType(value) {
      let bb = null
      this.schedulingType_list.forEach((e) => {
        if (e.dictValue === value) {
          bb = {
            key: e.dictKey,
            value: e.dictValue
          }
        }
      })
      this.formobj.schedulingTypeKey = bb.key
    },
    saveOrUpdate() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.saveOrUpdate(this.formobj).then((resp) => {
            this.submitdisabled = false
            if (resp.success) {
              this.$message({
                showClose: true,
                type: 'success',
                message: resp.msg
              })
              this.handleReturn('true')
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        } else {
          return false
        }
      })
    },
    submitVehicleApply() {
      req.submitVehicleApply(this.formobj).then((res) => {
        if (res.success) {
          this.$message({
            showClose: true,
            type: 'success',
            message: '提交成功'
          })
          this.handleReturn('true')
        } else {
          this.$message({
            showClose: true,
            type: 'error',
            message: '提交失败'
          })
        }
      })
    },
    handleShangZhuang(index) {
      this.viewState = 3
      this.$refs['divShangzhuangpeizhi'].showData(index)
    },
    backPeizhi(val, index) {
      this.viewState = 1
      const busVehicleApplySz = {
        color: '',
        coverPlate: '',
        floorHeating: '',
        otherConfig: '',
        overallDimension: '',
        plateMaterial: '',
        plateThickness: '',
        refitFactory: '',
        refitMethod: '',
        refrigerator: '',
        szSid: '',
        tarpaulinSlide: '',
        topName: '',
        vehicleFunction: '',
        costPrice: '',
        guidePrice: ''
      }
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz = busVehicleApplySz
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.color = val.colorValue
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.coverPlate = val.selfUnHyCoPl
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.floorHeating = val.floorHeating
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.otherConfig = val.moreConfig
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.overallDimension = val.wk
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.plateMaterial = val.plateMaterialValue
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.plateThickness = val.plateThickness
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.refitFactory = val.refitFactory
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.refitMethod = val.refitMethodValue
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.refrigerator = val.refrigerator
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.szSid = val.sid
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.tarpaulinSlide = val.tarpaulinSlide
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.topName = val.installNameValue
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.vehicleFunction = val.vehicleTypeValue
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.costPrice = ''
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz.guidePrice = ''
      this.formobj.busVehicleApplyDetailList[index].guidePrice = ''
    },
    handleUpdate(row, index) {
      if (row !== null && row !== undefined) {
        this.viewState = 4
        this.$refs['divShangzhuangpeizhiAdd'].showInfo(row, index)
      } else {
        this.$message({ showClose: true, type: 'success', message: '请先选择上装信息' })
      }
    },
    handleDel(index) {
      this.formobj.busVehicleApplyDetailList[index].guidePrice = ''
      this.$delete(this.formobj.busVehicleApplyDetailList[index], 'busVehicleApplySz')
    },
    backPeizhiAdd(value, index) {
      this.viewState = 1
      this.formobj.busVehicleApplyDetailList[index].busVehicleApplySz = value
      this.formobj.busVehicleApplyDetailList[index].guidePrice = value.guidePrice
      // for (var i = 0; i < this.formobj.busVehicleApplyDetailList.length; i++) {
      //   if (this.formobj.busVehicleApplyDetailList[i].busVehicleApplySz !== null && this.formobj.busVehicleApplyDetailList[i].busVehicleApplySz !== undefined) {
      //     if (this.formobj.busVehicleApplyDetailList[i].busVehicleApplySz.szSid === value.szSid) {
      //       this.formobj.busVehicleApplyDetailList[i].busVehicleApplySz = value
      //       this.formobj.busVehicleApplyDetailList[i].guidePrice = value.guidePrice
      //     }
      //   }
      // }
    },
    // 返回（===既判断）
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj.applyType = ''
      this.formobj.applyTypeKey = ''
      this.formobj.schedulingType = '' // 排产类型
      this.formobj.schedulingTypeKey = ''
      this.formobj.remarks = '' // 备注
      this.formobj.payRemarks = ''
      this.formobj.currentAmount = ''
      this.formobj.applicationCode = ''
      this.formobj.applicationDate = ''
      this.formobj.createBySid = ''
      this.formobj.createByName = ''
      this.formobj.taskId = ''
      this.formobj.instanceId = ''
      this.formobj.createOrgSid = ''
      this.formobj.createOrgName = ''
      this.formobj.busVehicleApplyDetailList = []
      this.$refs['form_obj'].resetFields()
      this.$emit('doback')
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '申请订金合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (column.property === 'applyForDeposit') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
          this.formobj.currentAmount = sums[index] += ''
        } else {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
            this.amount = sums[index] += ''
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
    closePage() {
      this.viewState = 1
    }
  }
}
</script>

<style scoped>
.title {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.spanOneWidth {
  border-right: 0px !important;
  width: 150px !important;
}
.addinputOne {
  margin-left: 150px !important;
}
.rowStyle {
  border-left: 0px;
}
.colStyle {
  border-right: 0px !important;
  border-bottom: 0px !important;
}
.colOneStyle {
  border-right: 0px !important;
}
</style>

