<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="submit()">提交</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="16">
              <div class="span-sty">申请编号</div>
              <el-form-item><span class="addinputInfo">{{ formobj.billNo }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <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">分公司</div>
              <el-form-item><span class="addinputInfo">{{ formobj.useOrgName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">申请部门</div>
              <el-form-item><span class="addinputInfo">{{ formobj.deptName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">申请人</div>
              <el-form-item><span class="addinputInfo">{{ formobj.createByName }}</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 prop="adjustWayKey">
                <el-select class="addinputInfo" v-model="formobj.adjustWayKey" placeholder="请选择" @change="changeAdjustWay" filterable clearable>
                  <el-option v-for="item in adjustWay_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div v-if="formobj.adjustWayKey == '001'">
                <div class="span-sty"><span class="icon">*</span>销售专员</div>
                <el-form-item prop="staffSid">
                  <el-select class="addinputInfo" v-model="formobj.staffSid" placeholder="请选择" @change="changeStaff" filterable clearable>
                    <el-option v-for="item in staff_list" :key="item.userSid" :label="item.name" :value="item.userSid"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div v-if="formobj.adjustWayKey == '001'">
                <div class="span-sty"><span class="icon">*</span>销售经理</div>
                <el-form-item prop="salesManageSid">
                  <el-select class="addinputInfo" v-model="formobj.salesManageSid" placeholder="请选择" @change="changeSalesManage" filterable clearable>
                    <el-option v-for="item in salesManager_list" :key="item.sid" :label="item.name" :value="item.sid"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <div class="title titleOne">
            <el-button size="mini" type="primary" class="btntopblueline" @click="handleSelect()">选择</el-button>
          </div>
          <el-table :key="tableKey" :data="formobj.list" :index="index" border style="width: 100%" show-summary :summary-method="getSummaries">
            <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="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="purchaseSystemName" label="采购系统" align="center" width="120" />
            <el-table-column prop="brandName" label="品牌" align="center" width="100" />
            <el-table-column prop="vehModelName" label="车型" align="center" min-width="160" />
            <el-table-column prop="vinNo" label="车架号" align="center" width="140" />
            <el-table-column prop="customerName" label="客户名称" align="center" width="120" />
            <el-table-column prop="contractNo" label="合同编号" align="center" width="170">
              <template slot-scope="scope">
                <span class="bluezi" @click="lookSales(scope.row.salesOrderSid)">{{ scope.row.contractNo }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="estimateRebate" label="订单贴息金额" align="center" width="150" />
            <el-table-column prop="uploadMoney" label="上传贴息金额" align="center" width="150" />
            <el-table-column prop="adjustmentMoney" label="差额" align="center" width="100" />
            <el-table-column prop="alreadyMoney" label="已调整金额" align="center" width="140" />
            <el-table-column prop="nowDiffAmount" label="当前差额" align="center" width="120" />
            <el-table-column prop="nowAdjustmentMoney" label="本次调整金额" align="center" width="160">
              <template slot-scope="scope">
                <el-input v-model="scope.row.nowAdjustmentMoney" @keyup.native="scope.row.nowAdjustmentMoney = getNumber(scope.row.nowAdjustmentMoney, 2)" clearable placeholder="" />
              </template>
            </el-table-column>
            <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>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">备注</div>
              <el-form-item><el-input class="addinputInfo" style="width: 80%" v-model="formobj.remarks" clearable placeholder="" /></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">附件</div>
              <el-form-item>
                <uploadImg ref="uploadImg" class="addinputInfo" v-model="formobj.filePath" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!-- 选择金融差异调整 -->
    <chooseAdjustment v-show="viewState == 2" ref="divChoose" @backData="backData" @doback="resetState" />
    <!-- 查看销售订单详情 -->
    <saleOrder v-show="viewState == 3" ref="divSales" @doback="resetState" />
  </div>
</template>

<script>
import req from '@/api/financialDiscount/financialDiscount'
import { getOrgSidByPath, fetchBySid, selectSysUserList, typeValues, selectStaffListByUseOrgSid } from '@/api/cheliang/dictcommons'
import uploadImg from '@/components/uploadFile/uploadImg'
import chooseAdjustment from './relation/chooseAdjustment'
import saleOrder from '@/components/publicPage/saleOrder'

export default {
  name: 'DifferenceManagementAdd',
  components: {
    uploadImg,
    chooseAdjustment,
    saleOrder
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      tableKey: 1,
      index: 0,
      adjustWay_list: [],
      staff_list: [],
      salesManager_list: [],
      formobj: {
        sid: '',
        createTime: '',
        createBySid: '',
        createByName: '',
        billNo: '',
        useOrgSid: '',
        useOrgName: '',
        deptName: '',
        deptSid: '',
        adjustWay: '',
        adjustWayKey: '',
        staffSid: '',
        staffName: '',
        salesManageSid: '',
        salesManage: '',
        remarks: '',
        taskId: '',
        instanceId: '',
        list: [],
        filePath: []
      },
      rules: {
        adjustWayKey: [{ required: true, message: '调整方式不能为空', trigger: 'change' }],
        staffSid: [{ required: true, message: '销售专员不能为空', trigger: 'change' }],
        salesManageSid: [{ required: true, message: '销售经理不能为空', trigger: 'change' }]
      }
    }
  },
  methods: {
    init() {
      typeValues({ type: 'adjustingWay' }).then((res) => {
        if (res.success) {
          this.adjustWay_list = res.data
        }
      })
      selectSysUserList({ userSid: window.sessionStorage.getItem('userSid'), orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((resp) => {
        if (resp.success) {
          this.salesManager_list = resp.data
        }
      })
    },
    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
    },
    showAdd() {
      this.viewTitle = '【新增】金融贴息差异调整申请'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      this.formobj.createByName = window.sessionStorage.getItem('name')
      this.formobj.createBySid = 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)
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((resp) => {
        if (resp.success) {
          this.formobj.useOrgSid = resp.data
          selectStaffListByUseOrgSid({ useOrgSid: resp.data }).then((res) => {
            if (res.success) {
              this.staff_list = res.data
            }
          })
          fetchBySid(resp.data).then((respsone) => {
            if (respsone.success) {
              this.formobj.useOrgName = respsone.data.name
            }
          })
        }
      })
    },
    showEdit(row) {
      this.viewTitle = '【编辑】金融贴息差异调整申请'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      req.fetchBySid(row.sid).then((res) => {
        if (res.success) {
          this.formobj = res.data
          selectStaffListByUseOrgSid({ useOrgSid: this.formobj.useOrgSid }).then((res) => {
            if (res.success) {
              this.staff_list = res.data
            }
          })
        }
      })
    },
    changeAdjustWay(value) {
      const choose = this.adjustWay_list.filter((item) => item.dictKey === value)
      if (choose !== null) {
        this.formobj.adjustWay = choose[0].dictValue
        if (this.formobj.adjustWay === '公司认损') {
          this.formobj.staffName = ''
          this.formobj.staffSid = ''
          this.formobj.salesManage = ''
          this.formobj.salesManageSid = ''
        }
      } else {
        this.formobj.adjustWay = ''
        this.formobj.staffName = ''
        this.formobj.staffSid = ''
        this.formobj.salesManage = ''
        this.formobj.salesManageSid = ''
      }
    },
    changeStaff(value) {
      const choose = this.staff_list.filter((item) => item.userSid === value)
      if (choose !== null) {
        this.formobj.staffName = choose[0].name
      } else {
        this.formobj.staffName = ''
      }
    },
    changeSalesManage(value) {
      const choose = this.salesManager_list.filter((item) => item.sid === value)
      if (choose !== null) {
        this.formobj.salesManage = choose[0].name
      } else {
        this.formobj.salesManage = ''
      }
    },
    handleSelect() {
      if (this.formobj.adjustWayKey === '001' && this.formobj.staffName === '') {
        this.$message({ showClose: true, type: 'error', message: '因调整方式为客户交纳，请先选择销售专员' })
        return
      }
      this.viewState = 2
      this.$refs['divChoose'].showData(this.formobj.list, this.formobj.useOrgSid, this.formobj.staffSid)
    },
    backData(value) {
      this.viewState = 1
      value = JSON.parse(JSON.stringify(value))
      value.forEach((e) => {
        this.formobj.list.push({
          rebateSid: e.rebateSid,
          checkApplySid: e.checkApplySid,
          purchaseSystemSid: e.purchaseSystemSid,
          purchaseSystemName: e.purchaseSystemName,
          brandSid: e.brandSid,
          brandName: e.brandName,
          vehModelSid: e.vehModelSid,
          vehModelName: e.vehModelName,
          vehSid: e.vehSid,
          vinNo: e.vinNo,
          customerSid: e.customerSid,
          customerName: e.customerName,
          contractNo: e.contractNo,
          salesOrderSid: e.salesOrderSid,
          estimateRebate: e.estimateRebate,
          uploadMoney: e.uploadMoney,
          adjustmentMoney: e.adjustmentMoney,
          alreadyMoney: e.alreadyMoney,
          nowDiffAmount: e.nowDiffAmount,
          nowAdjustmentMoney: '',
          remarks: ''
        })
      })
    },
    handleDelete(index) {
      this.formobj.list.splice(index, 1)
    },
    lookSales(sid) {
      this.viewState = 3
      this.$refs['divSales'].showInfo(sid)
    },
    resetState() {
      this.viewState = 1
    },
    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 === 'estimateRebate' || column.property === 'uploadMoney' || column.property === 'adjustmentMoney' || column.property === 'alreadyMoney' || column.property === 'nowDiffAmount' || column.property === 'nowAdjustmentMoney') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return Math.round((parseFloat(prev) + parseFloat(curr)) * 100) / 100
            } else {
              return Math.round((parseFloat(prev)) * 100) / 100
            }
          }, 0)
          sums[index] += ''
        }
      })
      return sums
    },
    saveOrUpdate() {
      if (this.formobj.list.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '列表不能为空' })
        return
      }
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.save(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
          })
        }
      })
    },
    submit() {
      if (this.formobj.list.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '列表不能为空' })
        return
      }
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.submit(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
          })
        }
      })
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        createTime: '',
        createBySid: '',
        createByName: '',
        billNo: '',
        useOrgSid: '',
        useOrgName: '',
        deptName: '',
        deptSid: '',
        adjustWay: '',
        adjustWayKey: '',
        staffSid: '',
        staffName: '',
        salesManageSid: '',
        salesManage: '',
        remarks: '',
        taskId: '',
        instanceId: '',
        list: [],
        filePath: []
      }
      this.submitdisabled = false
      this.$refs['form_obj'].resetFields()
      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);
}
/deep/ .el-form-item__error {
  margin-left: 120px !important;
}
.titleOne {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
}
</style>
