<template>
  <div class="app-container">
    <!-- Start 列表页面 -->
    <div v-show="viewState == 1">
      <button-bar view-title="待核对单车返利列表" ref="btnbar" :btndisabled="btndisabled" @btnhandle="btnHandle"/>
      <div class="main-content">
        <div class="switch_btn">
          <el-button :class="{btn_style:viewState === 1}">待核对</el-button>
          <el-button class="" @click="handleClick">核对审核申请</el-button>
        </div>
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="clicksearchShow">{{ searchxianshitit }}</el-button>
          <div v-show="isSearchShow" class="search">
            <el-form ref="listQueryform" :inline="true" :model="listQuery" label-width="100px" class="tab-header">
              <el-form-item label="品牌">
                <el-select v-model="listQuery.params.brandSid" placeholder="请选择" filterable clearable>
                  <el-option v-for="item in brand_list" :key="item.sid" :label="item.brandName" :value="item.sid"/>
                </el-select>
              </el-form-item>
              <el-form-item label="车架号">
                <el-input v-model="listQuery.params.vinNo" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="创建日期">
                <el-date-picker v-model="listQuery.params.createStartTime" type="date" clearable value-format="yyyy-MM-dd" placeholder="选择日期"/>
                <span style="padding: 0 8px">至</span>
                <el-date-picker v-model="listQuery.params.createEndTime" type="date" clearable value-format="yyyy-MM-dd" placeholder="选择日期"/>
              </el-form-item>
              <el-form-item label="返利类型">
                <el-select v-model="listQuery.params.rebateTypeKey" placeholder="请选择" filterable clearable>
                  <el-option v-for="item in rebateType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"/>
                </el-select>
              </el-form-item>
              <el-form-item label="返利名称">
                <el-input v-model="listQuery.params.rebateName" placeholder="" clearable/>
              </el-form-item>
<!--              <el-form-item label="上传状态">-->
<!--                <el-select v-model="listQuery.params.state" placeholder="请选择" filterable clearable>-->
<!--                  <el-option v-for="item in state_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"/>-->
<!--                </el-select>-->
<!--              </el-form-item>-->
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" icon="el-icon-search" @click="handleFilter" size="small">查询</el-button>
              <el-button type="primary" icon="el-icon-refresh" @click="handleReset" size="small">重置</el-button>
            </div>
          </div>
        </div>
        <div class="listtop">
          <div class="tit">单车返利待核对列表</div>
          <div>
            <el-button size="mini" type="success">导入</el-button>
            <el-button size="mini" type="success">导出</el-button>
          </div>
        </div>
        <div class="">
          <el-table :key="tableKey" v-loading="listLoading" :data="list" border style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column fixed type="selection" align="center" width="50px"/>
            <el-table-column fixed label="序号" type="index" :index="indexMethod" align="center" width="80px"/>
            <el-table-column label="上传状态" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.uploadState == '0' ? '未调整' : scope.row.uploadState == '1' ? '已调整' : scope.row.uploadState == '2' ? '未上传' : scope.row.uploadState == '3' ? '已上传' : ''}}</span>
              </template>
            </el-table-column>
            <el-table-column label="品牌" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.brandName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="车型" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.vehModelName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="车架号" align="center" width="250">
              <template slot-scope="scope">
                <span>{{ scope.row.vinNo }}</span>
              </template>
            </el-table-column>
            <el-table-column label="厂家结算价" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.manufactorSettlementPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="其中运费" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.freight }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建日期" align="center" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="返利名称" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.rebateName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="返利类型" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.rebateTypeValue }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预计返利" align="center" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.estimateRebate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所属年月" align="center" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.palceGenDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上传日期" align="center" width="200">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.uploadDate" type="date" style="width: 160px" clearable value-format="yyyy-MM-dd" placeholder="选择日期"/>
              </template>
            </el-table-column>
            <el-table-column label="上传金额" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.uploadMoney" @keyup.native="UpNumber" @keydown.native="UpNumber" clearable placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column label="二次上传日期" align="center" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.secondaryUploadDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="二次上传金额" align="center" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.secondaryUploadMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="待确定金额" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stayDetermineMoney" @keyup.native="UpNumber" @keydown.native="UpNumber" clearable placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column label="费用" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.money" @keyup.native="UpNumber" @keydown.native="UpNumber" clearable placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column label="是否调整" align="center" width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.isAdjustment" :disabled="scope.row.stayDetermineMoney > 0 || (scope.row.stayDetermineMoney == '0' && scope.row.adjustmentMoney == '0')" @change="changeIsAdjustment(scope.row)" placeholder="" filterable>
                  <el-option v-for="item in whether_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="调整金额" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.adjustmentMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="调整说明" align="center" width="300">
              <template slot-scope="scope">
                <el-input :disabled="scope.row.isAdjustment === '' || scope.row.isAdjustment === '否'" v-model="scope.row.adjustmentRemarks" clearable placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180px" >
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="toSave(scope.row)">保存</el-button>
                <el-button type="primary" :disabled="scope.row.isAdjustment === '' || scope.row.isAdjustment === '是'" size="mini" @click="toAdjust(scope.row)">调整</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pages">
          <!-- 翻页 -->
          <pagination v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
      </div>
    </div>
    <bicyclerebatecheck v-show="viewState == 2" ref="divCheck" @doback="resetState"/>
    <bicyclerebatecheckAdd v-show="viewState == 3" ref="divCheckAdd" @doback="resetState"/>
    <el-dialog center :visible.sync="dialogVisible" width="60%">
      <div class="app-container">
        <div class="tab-header webtop">
          <!--标题-->
          <div>{{ viewTitle }}</div>
          <!--start 添加修改按钮-->
          <div>
            <el-button type="primary" size="small" :disabled="submitdisabled" @click="handleSave()">保存
            </el-button>
            <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
          </div>
        </div>
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formadd">
          <div class="title">
            <div><span>待确定金额</span></div>
          </div>
          <el-row style="border-top: 1px solid #E0E3EB">
            <el-col :span="4" class="tleftb">
              <span>待确定金额</span>
            </el-col>
            <el-col :span="4">
              <el-form-item><span>{{ formobj.stayDetermineMoney }}</span></el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>其中含费用</span>
            </el-col>
            <el-col :span="4">
              <el-form-item><el-input v-model="formobj.firstCost" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="4" class="tleftb">
              <span>其中含返利</span>
            </el-col>
            <el-col :span="4">
              <el-form-item><el-input v-model="formobj.firstRebate" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <div class="title">
            <el-checkbox v-model="checked"><span style="color: #FFFFFF">返利二次上传</span></el-checkbox>
          </div>
          <div v-if="checked">
            <el-row>
              <el-col :span="4" class="tleftb">
                <span>剩余预计返利</span>
              </el-col>
              <el-col :span="4">
                <el-form-item><span>{{ formobj.surplusRebate}}</span></el-form-item>
              </el-col>
              <el-col :span="4">
              </el-col>
              <el-col :span="4">
              </el-col>
              <el-col :span="4" class="tleftb">
                <span>二次上传日期</span>
              </el-col>
              <el-col :span="4">
                <el-form-item><el-date-picker v-model="formobj.secondaryUploadDate" type="date" clearable value-format="yyyy-MM-dd" style="width: 100%" placeholder="选择日期"/></el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="4" class="tleftb">
                <span>二次上传金额</span>
              </el-col>
              <el-col :span="4">
                <el-form-item><el-input v-model="formobj.secondaryUploadMoney" clearable placeholder=""/></el-form-item>
              </el-col>
              <el-col :span="4" class="tleftb">
                <span>其中含费用</span>
              </el-col>
              <el-col :span="4">
                <el-form-item><el-input v-model="formobj.secondCost" clearable placeholder=""/></el-form-item>
              </el-col>
              <el-col :span="4" class="tleftb">
                <span>其中含返利</span>
              </el-col>
              <el-col :span="4">
                <el-form-item><el-input v-model="formobj.secondRebate" clearable placeholder=""/></el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="4" class="tleftb">
                <span>调整金额合计</span>
              </el-col>
              <el-col :span="20">
                <el-form-item><span>{{ adjustmentMoneyAdd() }}</span></el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import req from '@/api/bikerebate/bicyclerebatecheck'
import Pagination from '@/components/pagination'
import ButtonBar from '@/components/ButtonBar'
import bicyclerebatecheck from './bicyclerebatecheck'
import bicyclerebatecheckAdd from './bicyclerebatecheckAdd'
import { brandDown, getOrgSidByPath, typeValues } from '@/api/cheliang/dictcommons'

export default {
  name: 'BicycleRebateToBeChecked',
  components: {
    Pagination,
    ButtonBar,
    bicyclerebatecheck,
    bicyclerebatecheckAdd
  },
  data() {
    return {
      btndisabled: false,
      dialogVisible: false,
      btnList: [
        {
          type: 'primary',
          size: 'small',
          icon: '',
          btnKey: 'toAdd',
          btnLabel: '核对审核申请'
        },
        {
          type: 'primary',
          size: 'small',
          icon: '',
          btnKey: 'toClick',
          btnLabel: '调整'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      isSearchShow: false,
      searchxianshitit: '显示查询条件',
      viewState: 1,
      // 查询条件 -----------
      tableKey: 0,
      list: [],
      sids: [],
      FormLoading: false,
      brand_list: [],
      rebateType_list: [],
      state_list: [
        {
          dictKey: 1,
          dictValue: '未上传'
        },
        {
          dictKey: 3,
          dictValue: '已上传'
        }
      ],
      whether_list: [
        {
          dictKey: 0,
          dictValue: '否'
        },
        {
          dictKey: 1,
          dictValue: '是'
        }
      ],
      listLoading: false,
      listQuery: {
        params: {
          brandSid: '',
          createOrgSid: '',
          vinNo: '',
          rebateTypeKey: '',
          rebateName: '',
          state: '',
          createEndTime: '',
          createStartTime: '',
          orgPath: '',
          userSid: '',
          menuUrl: ''
        },
        current: 1,
        size: 5,
        total: 0
      },
      rules: {},
      viewTitle: '返利调整',
      submitdisabled: false,
      checked: false,
      formobj: {
        sid: '',
        stayDetermineMoney: '',
        firstCost: '',
        firstRebate: '',
        surplusRebate: '',
        secondaryUploadDate: '',
        secondaryUploadMoney: '',
        secondCost: '',
        secondRebate: '',
        adjustmentMoney: ''
      }
    }
  },
  created() {
    // 加载列表
    this.init()
  },
  mounted() {
    this.$refs['btnbar'].setButtonList(this.btnList)
  },
  methods: {
    init() {
      typeValues({ type: 'rebateType' }).then((res) => {
        if (res.success) {
          this.rebateType_list = res.data
        }
      })
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((resp) => {
        if (resp.success) {
          this.listQuery.params.createOrgSid = resp.data
          brandDown({ useOrg: this.listQuery.params.createOrgSid }).then((res) => {
            if (res.success) {
              this.brand_list = res.data
            }
          })
          this.getList()
        }
      })
    },
    // 搜索条件效果
    clicksearchShow() {
      this.isSearchShow = !this.isSearchShow
      if (this.isSearchShow) {
        this.searchxianshitit = '隐藏查询条件'
      } else {
        this.searchxianshitit = '显示查询条件'
      }
    },
    btnHandle(btnKey) {
      console.log('XXXXXXXXXXXXXXX    ' + btnKey)
      switch (btnKey) {
        case 'toAdd':
          this.toAdd()
          break
        case 'doImport':
          this.doImport()
          break
        case 'doClose':
          this.doClose()
          break
        default:
          break
      }
    },
    // 序号
    indexMethod(index) {
      var pagestart = (this.listQuery.current - 1) * this.listQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    handleSelectionChange(row) {
      const aa = []
      row.forEach((element) => {
        aa.push(element.sid)
      })
      this.sids = aa
      console.log('sids', this.sids)
    },
    // 查询列表信息
    getList() {
      this.listLoading = true
      this.listQuery.params.userSid = window.sessionStorage.getItem('userSid')
      this.listQuery.params.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      this.listQuery.params.menuUrl = this.$route.path
      req.listPage(this.listQuery).then((response) => {
        console.log('列表查询结果：', response)
        this.listLoading = false
        if (response.success && response.data && response.data.total > 0) {
          this.list = response.data.records
          this.listQuery.total = response.data.total
        } else {
          this.list = []
          this.listQuery.total = 0
        }
      })
    },
    // 查询按钮
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        params: {
          brandSid: '',
          createOrgSid: '',
          vinNo: '',
          rebateTypeKey: '',
          rebateName: '',
          state: '',
          createEndTime: '',
          createStartTime: '',
          orgPath: '',
          userSid: '',
          menuUrl: ''
        },
        current: 1,
        size: 5,
        total: 0
      }
      this.init()
    },
    UpNumber(e) {
      e.target.value = e.target.value.replace(/[^\d]/g, '') // 清除“数字”和“.”"-"以外的字符
      e.target.value = e.target.value.replace(/^00/, '0') // 开头不能有两个0
      if (e.target.value.indexOf('.') < 0 && e.target.value !== '' && e.target.value !== '-') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        console.log(e.target.value)
        e.target.value = parseFloat(e.target.value)
      }
    },
    changeIsAdjustment(row) {
      if (row.isAdjustment === '是') {
        if (row.uploadMoney === '') {
          row.isAdjustment = ''
          this.$message({ showClose: true, type: 'error', message: '上传金额不能为空' })
          return
        }
        if (row.money === '') {
          row.isAdjustment = ''
          this.$message({ showClose: true, type: 'error', message: '费用不能为空' })
          return
        }
        if (row.stayDetermineMoney === '') {
          row.isAdjustment = ''
          this.$message({ showClose: true, type: 'error', message: '待确定金额不能为空' })
          return
        }
        if (row.uploadMoney !== '' && row.money !== '' && row.stayDetermineMoney !== '') {
          row.adjustmentMoney = parseInt(row.uploadMoney) - parseInt(row.money) - parseInt(row.stayDetermineMoney) - parseInt(row.estimateRebate)
        }
      } else if (row.isAdjustment === '否') {
        row.adjustmentMoney = 0
        row.adjustmentRemarks = ''
      }
    },
    adjustmentMoneyAdd() {
      this.formobj.adjustmentMoney = parseInt(this.formobj.firstRebate - 0) + parseInt(this.formobj.secondRebate - 0) - parseInt(this.formobj.surplusRebate - 0)
      return this.formobj.adjustmentMoney
    },
    handleSave() {
      let aa = null
      if (!this.checked) {
        aa = {
          sid: this.formobj.sid,
          stayDetermineMoney: 0,
          cost: this.formobj.firstCost,
          secondaryUploadDate: '',
          secondaryUploadMoney: 0,
          adjustmentMoney: this.formobj.firstRebate
        }
      } else {
        aa = {
          sid: this.formobj.sid,
          stayDetermineMoney: 0,
          cost: parseInt(this.formobj.firstCost) + parseInt(this.formobj.secondCost),
          secondaryUploadDate: this.formobj.secondaryUploadDate,
          secondaryUploadMoney: this.formobj.secondaryUploadMoney,
          adjustmentMoney: this.formobj.adjustmentMoney
        }
      }
      req.adjustment(aa).then((resp) => {
        if (resp.success) {
          this.$message({ showClose: true, type: 'success', message: '保存成功' })
          this.getList()
          this.handleReturn()
        }
      })
    },
    handleReturn() {
      this.dialogVisible = false
      this.formobj = {
        sid: '',
        stayDetermineMoney: '',
        firstCost: '',
        firstRebate: '',
        surplusRebate: '',
        secondaryUploadDate: '',
        secondaryUploadMoney: '',
        secondCost: '',
        secondRebate: '',
        adjustmentMoney: ''
      }
      this.checked = false
    },
    handleClick() {
      this.viewState = 2
    },
    toAdd() {
      this.viewState = 3
      this.$refs['divCheckAdd'].showAdd(this.listQuery.params.createOrgSid)
    },
    toSave(row) {
      if (row.uploadDate === '') {
        this.$message({ showClose: true, type: 'error', message: '上传日期不能为空' })
        return
      }
      if (row.uploadMoney === '') {
        this.$message({ showClose: true, type: 'error', message: '上传金额不能为空' })
        return
      }
      if (row.stayDetermineMoney === '') {
        this.$message({ showClose: true, type: 'error', message: '待确定金额不能为空' })
        return
      }
      if (row.money === '') {
        this.$message({ showClose: true, type: 'error', message: '费用不能为空' })
        return
      }
      if (row.stayDetermineMoney !== '0') {
        if (row.isAdjustment === '是') {
          this.$message({ showClose: true, type: 'error', message: '因待确定金额大于0,是否调整选项需选择否' })
          return
        }
      } else if (row.stayDetermineMoney === '0') {
        if (row.adjustmentMoney.toString().indexOf('-') !== -1) {
          if (row.isAdjustment === '是') {
            this.$message({ showClose: true, type: 'error', message: '因待确定金额等于0且调整金额小于0,是否调整选项需选择否' })
            return
          }
        } else if (row.adjustmentMoney !== '0') {
          if (row.isAdjustment === '否') {
            if ((parseInt(row.uploadMoney) - parseInt(row.estimateRebate)) > 0) {
              this.$message({ showClose: true, type: 'error', message: '因待确定金额等于0且调整金额大于0,是否调整选项需选择是' })
              return
            }
          }
        } else if (row.adjustmentMoney === '0') {
          if (row.isAdjustment === '否') {
            this.$message({ showClose: true, type: 'error', message: '因待确定金额等于0且调整金额等于0,是否调整选项需选择是' })
            return
          }
        }
      }
      if (row.isAdjustment === '是') {
        if (row.adjustmentMoney === '') {
          this.$message({ showClose: true, type: 'error', message: '调整金额不能为空' })
          return
        }
        if (row.adjustmentRemarks === '') {
          this.$message({ showClose: true, type: 'error', message: '调整说明不能为空' })
          return
        }
      }
      req.updateDate(row).then((resp) => {
        if (resp.success) {
          this.$message({ showClose: true, type: 'success', message: '保存成功' })
          this.getList()
        }
      })
    },
    toInfo(row) {
      this.viewState = 4
      this.$refs['divInfo'].showInfo(row)
    },
    toAdjust(row) {
      this.dialogVisible = true
      this.formobj.stayDetermineMoney = row.stayDetermineMoney
      this.formobj.sid = row.sid
      this.formobj.firstCost = 0
      this.formobj.firstRebate = 0
      this.formobj.secondCost = 0
      this.formobj.secondRebate = 0
      this.formobj.secondaryUploadMoney = 0
      this.formobj.surplusRebate = parseInt(row.estimateRebate) - parseInt(row.uploadMoney)
    },
    resetState() {
      this.viewState = 1
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
.switch_btn {
  padding: 15px 0 10px 0;
}
.btn_style {
  background-color: #018ad2;
  color: white;
  font-weight: 600;
}
</style>
