<template>
  <div>
    <el-button size="mini" type="primary" @click="dialogFormVisible = true;form.billnodate=new Date()">新 建</el-button>
    <el-drawer title="新建核销单" append-to-body :show-close="false" :visible.sync="dialogFormVisible" size="60%">
      <div class="drawer__panel">
        <el-row>
          <el-form :model="form" :rules="rules" ref="form" label-width="90px" label-position="right" size="mini">
            <el-col :span="12">
              <el-form-item label="经销商:" prop="sys_enterpriseid">
                <selectEnterprise ref="ent" @rowClick="entRowClick"></selectEnterprise>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账户类型" prop="sa_accountclassid">
                <el-select v-model="form.sa_accountclassid" placeholder="请选择账户类型" @change="accountChange" size="small">
                  <el-option
                    v-for="item in accountType"
                    :key="item.sa_accountclassid"
                    :label="item.accountname"
                    :value="item.sa_accountclassid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="凭证" prop="sa_cashbillid">
                <selectVoucher ref="voucher" v-model="form.sa_cashbillid" :sys_enterpriseid="form.sys_enterpriseid" :sa_accountclassid="form.sa_accountclassid" @rowClick="voucherRowClick"></selectVoucher>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="核销金额" prop="writeoffamount">
                <el-input size="small" placeholder="请输入核销金额" v-model.number="form.writeoffamount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="核销日期" prop="billnodate">
                <el-date-picker
                  v-model="form.billnodate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="订单">
                <div class="flex-align-center flex-between mt-10">
                  <el-input 
                    style="width:200px" 
                    size="small"  
                    suffix-icon="el-icon-search" 
                    v-model="params.content.where.condition" placeholder="搜索" 
                    @keyup.enter.native="getOrderList(params.content.pageNumber = 1)" @clear="getOrderList(params.content.pageNumber = 1)" clearable></el-input>
                </div>
                <selectOrder v-if="dialogFormVisible" ref="table" idName="sa_orderitemsid" :layout="tablecols" :data="orderList" :custom="true" height="500px">
                  <template v-slot:customcol="scope">
                      <div>{{scope.column.data[scope.column.columnname]}}</div>
                  </template>
                </selectOrder>
                <div class="container normal-panel" style="text-align:right">
                  <el-pagination
                      style="text-align:right"
                      background
                      small
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="params.content.pageNumber"
                      :page-size="params.content.pageSize"
                      layout="total,sizes, prev, pager, next, jumper"
                      :total="total">
                  </el-pagination>
                </div>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div class="fixed__btn__panel">
        <el-button size="small" @click="dialogFormVisible = false" class="normal-btn-width">取 消</el-button>
        <el-button size="small" type="primary" @click="onSubmit" class="normal-btn-width">确 定</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import selectEnterprise from './selectEnterprise'
import selectVoucher from './selectVoucher'
import selectOrder from '../modules/order/selectOrder'
export default {
  name: "add",
  components:{selectEnterprise,selectVoucher,selectOrder},
  data(){
    return {
      dialogFormVisible:false,
      accountType:[],
      tablecols:[],
      total:0,
      orderList:[],
      form:{
        "sa_writeoffbillid":0,
        "sys_enterpriseid": "",
        "sa_accountclassid": "",
        "sa_cashbillid":"",
        "remarks":"",
        "writeoffamount":0,  //新增时可不传
        "billnodate": ''
      },
      rules:{
        sys_enterpriseid:[
          { required: true, message: '请选择经销商', trigger: 'blur'},
        ],
        sa_accountclassid:[
          { required: true, message: '请选择账户类型', trigger: 'blur'}
        ],
        sa_cashbillid:[
          { required: true, message: '请选择支出或收入凭证', trigger: 'change'}
        ],
        writeoffamount:[
          { message: '请填写正确金额', trigger: 'blur',type:'number'}
        ],
      },
      params: {
        "id": 20221124091104,
        "content": {
          "pageNumber": 1,
          "pageSize": 20,
          "sys_enterpriseid":'',
          "sa_accountclassid":'',
          "sa_writeoffbillid":'',
          "where": {
              "condition": ""
          }
        }
      }
    }
  },
  created () {
    this.getAccountType()
    this.tablecols = this.tool.tabelCol(this.$route.name).addOrderTable.tablecols
  },
  watch: {
    dialogFormVisible (val) {
      if(!val) {
        this.$refs.ent.form.enterprisename = ''
        this.$refs.form.resetFields()
        this.$refs.table.allArr = []
        this.orderList = []
        this.$refs.voucher.form.billno = ''
        this.form.sa_cashbillid = ''
      }
    }
  },
  methods:{
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.content.pageSize = val
      this.getOrderList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.content.pageNumber = val
      this.getOrderList()
    },
    async getOrderList () {
      if(!this.form.sa_accountclassid || !this.form.sys_enterpriseid) return

      this.$refs.table.allArr = []

      this.params.content.sys_enterpriseid = this.form.sys_enterpriseid
      this.params.content.sa_accountclassid = this.form.sa_accountclassid
      let res = await this.$api.requested(this.params)
      this.orderList = res.data
      this.total = res.total
      console.log(res);
    },
    onSubmit(){
      console.log(this.form)
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false
        const res = await this.$api.requested({
          "id": "20221124090204",
          "version":1,
          "content": this.form
        })
        this.tool.showMessage(res,async ()=>{
          let result = this.$refs.table.allArr.map(item => {
            return {
              "sa_writeoffbill_orderid": 0,
              "sa_orderid":item.sa_orderid,
              "sa_orderitemsid":item.sa_orderitemsid,
              "writeoffamount":0,
              "remarks":""
            }
          })
          if (result.length > 0) {
            const res2 = await this.$api.requested({
              "id": "20221124090904",
              "version":1,
              "content": {
                sa_writeoffbillid:res.data[0].sa_writeoffbillid,
                writeoffbillOrder:result
              }
            })
          }
          this.$emit('onSuccess')
          this.dialogFormVisible = false
          this.$store.dispatch('changeDetailDrawer',true)
          this.$router.push({path:'/writeoffbillDetail',query:{id:res.data[0].sa_writeoffbillid,rowindex:res.data[0].rowindex}})
        })
      })
    },
    entRowClick (data) {
      this.$refs.voucher.form.billno = ''
      this.form.sa_cashbillid = ''
      this.form.sys_enterpriseid = data.sys_enterpriseid
      this.getOrderList()
    },
    voucherRowClick (data) {
      this.form.sa_cashbillid = data.sa_cashbillid
    },
    async getAccountType () {
      let res = await this.$api.requested({
        "id":20221124090604,
        "content": {

        }
      })
      this.accountType = res.data
    },
    accountChange (val) {
      this.$refs.voucher.form.billno = ''
      this.form.sa_cashbillid = ''
      this.getOrderList()
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  margin-top: 0;
}
.el-select {
  width: 100%;
}
</style>