<template>
  <div>
    <el-button v-if="data.status ==='新建'"  type="primary" size="mini" @click="onShow(drawer = true)">编 辑</el-button>
    <!-- <el-button type="primary" size="mini" @click="onShow(drawer = true)">编 辑</el-button> -->
    <el-drawer
    :visible.sync="drawer"
    direction="rtl"
    append-to-body
    size="80%">
    <div slot="title">
      <div class="flex-align-center">
        <p><span style="font-size:14px">订单合计:</span><span style="color:red;font-size:16px;"><b>¥&nbsp;{{tool.formatAmount(data.amount,2)}}</b></span></p>
        <!-- <label style="font-size:14px;margin-left:10px" for="">备注:</label>
        <input class="order__note__input" v-model="defaultData.remarks" type="text" placeholder="请输入订单备注"> -->
         <p>运费:{{data.amount > data.freefreightamount >= 0?'当前订单免运费':`订单满${data.freefreightamount}元免运费,当前还差${data.freefreightamount - data.amount}元`}}</p>
      </div>
    </div>
    <div class="drawer__panel">
      <!-- 经销商信息 -->
      <div class="reveive__panel normal-margin flex-align-center">
        <p class="inline-16"><small>经销商编号:&nbsp;</small>{{data.agentnum}}</p>
        <p class="inline-16"><small>经销商名称:&nbsp;</small>{{data.enterprisename}}</p>
        <p class="inline-16"><small>领域:&nbsp;</small>{{data.tradefield}}</p>
        <p class="inline-16"><small>品牌:&nbsp;</small>{{data.brandname}}</p>
        <div class="flex-align-center">
          <small>所属业务员:&nbsp;</small>{{saler_name}}
          <selectSaler @selectRow="selectRow" ref="saler">
            <el-button type="text" size="mini" slot="input"  @click="$refs['saler'].visible = true">&nbsp;更换业务员</el-button>
          </selectSaler>
        </div>
      </div>
      <!-- 项目订单显示信息 -->
      <div v-if="data.type === '项目订单'" class="reveive__panel normal-margin flex-align-center">
        <p class="inline-16"><small>项目信息:&nbsp;</small>{{data.projectname}}</p>
        <p class="inline-16"><small>合同信息:&nbsp;</small>{{data.contract_title}}</p>
      </div>
      <div>
        <div class="mt-10">
          <p class="normal-title inline-16">支付信息</p>
        </div>
        <div class="reveive__panel normal-margin">
          <p class="flex-align-center"><small>结算企业:&nbsp;</small><b>{{defaultData.finance.enterprisename}}</b>&nbsp;<financeEnterprise v-if="data.type !== '项目订单'" :sys_enterpriseid="data.sys_enterpriseid" @select="onSelect"></financeEnterprise></p>
          <div class="flex-align-center">
            <p class="inline-16"><small>账户余额:&nbsp;</small><b>¥{{tool.formatAmount(defaultData.accountclass.balance?defaultData.accountclass.balance:0,2)}}</b></p>
            <p class="inline-16"><small>账户名称:&nbsp;</small>{{defaultData.accountclass.accountname?defaultData.accountclass.accountname:'未选择账户'}}</p>
            <p><small>本单金额:&nbsp;</small>{{tool.formatAmount(data.amount - rebateamount,2)}}</p>
          </div>
          <div v-if="(data.type === '标准订单' ||  data.type === '特殊订单') && isusedrebate === 1">
            <el-checkbox v-model="checked" :true-label="1" :false-label="0">使用返利金</el-checkbox>
            <div v-if="checked" class="flex-align-center">
              <p class="inline-16"><b>返利金余额:{{tool.formatAmount(defaultData.rebatebalance,2)}}</b></p>
              <el-input class="inline-16" size="mini" style="width:150px" v-model="rebateamount" @blur="useRebate" placeholder="输入使用金额"></el-input>
              <small>(返利金最高使用比例{{data.order_rebate_userate}}%,本单上限:{{tool.formatAmount(data.amount * data.order_rebate_userate / 100,2)}})</small>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-align-start normal-margin">
        <div style="flex:1; margin-right:10px">
          <div class="mt-10">
            <p class="normal-title inline-16">选择财务信息</p>
            <el-popover
              placement="bottom"
              title="选择财务信息"
              trigger="click"
              v-model="visible2">
              <el-table
                :data="financiallist"
                style="width: 100%"
                size="mini">
                <el-table-column
                  prop="enterprisename"
                  label="公司抬头"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="address"
                  label="开票地址"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="bank"
                  label="开户行"
                  width="120">
                </el-table-column>
                <el-table-column
                  prop="bankcardno"
                  label="开户账号"
                  width="120">
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="90">
                  <template slot-scope="scope">
                    <el-button type="text" @click="(defaultData.fin_info = scope.row,visible2 = false)" size="mini">选 择</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button slot="reference" type="text" size="mini">选择其他</el-button>
            </el-popover>
          </div>
          <div class="reveive__panel normal-margin">
            <p><small>抬头:&nbsp;</small><span class="inline-16"><b>{{defaultData.fin_info.enterprisename}}</b></span></p>
            <p class="inline-16"><small>开票地址:&nbsp;</small>{{defaultData.fin_info.address?defaultData.fin_info.address:'--'}}</p>
            <p><small>开户行:&nbsp;</small> {{defaultData.fin_info.bank}} &emsp;<small>开户账号:&nbsp;</small> {{defaultData.fin_info.bankcardno}}</p>
          </div>
        </div>
        <div style="flex:1;">
          <div class="mt-10">
            <p class="normal-title inline-16">收货信息</p>
            <el-popover
              placement="bottom"
              title="选择地址"
              trigger="click"
              v-model="visible">
              <el-table
                :data="receiveAddresslist"
                style="width: 100%"
                size="mini">
                <el-table-column
                  prop="name"
                  label="联系人"
                  width="90">
                </el-table-column>
                <el-table-column
                  prop="phonenumber"
                  label="电话"
                  width="120">
                </el-table-column>
                <el-table-column
                  label="地址"
                  width="360">
                  <template slot-scope="scope">
                    {{scope.row.province}}{{scope.row.city}}{{scope.row.county}}{{scope.row.address}}
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="90">
                  <template slot-scope="scope">
                    <el-button type="text" @click="(defaultData.re_info = scope.row,visible = false)" size="mini">选 择</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button slot="reference" type="text" size="mini">选择其他地址</el-button>
            </el-popover>
          </div>
          <div class="reveive__panel normal-margin">
            <p><span class="inline-16"><b>{{defaultData.re_info.name}}</b></span><small>{{defaultData.re_info.phonenumber}}</small></p>
            <small>{{defaultData.re_info.province?defaultData.re_info.province:'--'}}{{defaultData.re_info.city}}{{defaultData.re_info.county}}{{defaultData.re_info.address?defaultData.re_info.address:''}}</small>
          </div>
        </div>
        
      </div>
      <div class="normal-margin flex-align-center">
        <div class="inline-16">
          <small><b>回签单</b>&nbsp;</small>
          <el-radio-group v-model="signbackstatus">
            <el-radio label="不需要">不需要</el-radio>
            <el-radio label="纸质件">纸质件</el-radio>
            <el-radio label="扫描件">扫描件</el-radio>
          </el-radio-group>
        </div>
        <div style="margin-left:20px">
          <small><b>销售类别:</b>&nbsp;</small>
          <el-select v-model="saletype" size="small" placeholder="请选择">
            <el-option
              v-for="item in saleroptions"
              :key="item.value"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div style="margin-left:20px">
          <small><b>单据日期:</b>&nbsp;</small>
          <el-date-picker
            v-model="billdate"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </div>
      </div>
      <div class="normal-margin">
        <p class="normal-title mt-10 inline-16">订单备注</p>
        <el-input size="mini" class="order__note__input" type="textarea" v-model="defaultData.remarks" :autosize="{minRows:5}" placeholder="请输入订单备注"></el-input>
      </div>
      <div class="mt-10">
        <div>
          <p class="normal-title inline-16">订单产品</p>
          <el-button type="text" size="mini" @click="addMoreProduct">{{setcol === 12?'关闭选择':'添加产品'}}</el-button>
        </div>
        <el-row :gutter="10">
          <el-col :span="setcol">
            <product-list ref="prolist" :data="data" :type="'edit'" @onSuccess="onEditSuccess"></product-list>
          </el-col>
          <el-col :span="24 - setcol">
            <add-product ref="addpro" :data="data" @onConfirm="onConfirm"></add-product>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="fixed__btn__panel">
      <el-button size="small" @click="drawer = 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 previewImage from '@/components/previewImage/index.vue'
import productList from '../details/tabs/productlist.vue'
import addProduct from '@/template/orderCanUseProduct/index.vue'
import financeEnterprise from '@/template/orderCanUseFinance/index.vue'
import selectSaler from '@/template/selectSaler/index.vue'

export default {
  props:['data'],
  components:{
    selectSaler,
    previewImage,
    productList,
    addProduct,
    financeEnterprise
  },
  data () {
    return {
      checked:0,
      visible:false,
      visible1:false,
      visible2:false,
      visible3:false,
      drawer:false,
      receiveAddresslist:[],
      accountlist:[],
      rebateAccount:[],
      logisticcomlist:[],
      financiallist:[],
      saleroptions:[],
      defaultData:{
        re_info:{},
        logist_info:{},
        fin_info:{},
        finance:{},
        accountclass:{},
        account_index:0,
        remarks:this.data.remarks
      },
      total:0,
      setcol:24,
      rebateamount:null,
      isusedrebate:0,
      signbackstatus:'不需要',
      saletype:"",
      saler_name:"",
      billdate:''
    }
  },
  methods:{
    onShow () {
      this.initPage()
    },
    async initPage () {

      this.setDefaultData()

      this.receiveAddress()

      this.queryUsedrebate()

      this.selectOptions()

      this.checked = this.data.rebate_used
      this.rebateamount = this.data.rebateamount
    },
    // 收货信息:合作企业联系人
    async receiveAddress (fn) {
      const res = await this.$api.requested({
        "id": "20230220002602",
        "content": {
          "sys_enterpriseid": this.data.sys_enterpriseid,
          "where": {
              "condition": ""
          }
        },
      })
      this.receiveAddresslist = res.data
    },

    // 设置默认信息
    async setDefaultData () {
      this.defaultData.rebatebalance = this.data.rebatebalance
      this.defaultData.finance = this.data.finance
      this.defaultData.fin_info = this.data.finance
      this.defaultData.accountclass = this.data.accountclass
      this.defaultData.re_info = this.data.contacts
      this.financiallist = this.data.pay_finance
      this.saletype = this.data.saletype
      this.signbackstatus = this.data.signbackstatus
      this.saler_name = this.data.saler_name
      this.billdate = this.data.billdate
    },
   
    async onSubmit() {
      const res = await this.$api.requested({
        "id": 20221108111402,
        "content": {
          "sa_orderid": this.$route.query.id,
          "sys_enterpriseid": this.data.sys_enterpriseid, //订货企业id
          "sa_accountclassid": this.defaultData.accountclass.sa_accountclassid, //营销账户类型ID
          "sa_brandid": this.data.sa_brandid, //品牌ID
          "sa_contractid":this.data.sa_contractid, //合同ID，标准订单不传
          "sa_projectid": this.data.sa_projectid, //工程项目表ID，标准订单不传
          "sys_enterprise_financeid": this.defaultData.fin_info.sys_enterprise_financeid, //合作企业财务信息ID（开票信息）
          "sa_logiscompid": this.defaultData.logist_info.sa_logiscompid, //物流公司档案ID
          "rec_contactsid": this.defaultData.re_info.contactsid, //合作企业联系人表ID（收货信息）
          "type": this.data.type, //订单类型
          "typemx":this.data.typemx, //明细分类，可选
          "remarks": this.defaultData.remarks, //可选
          "saler_hrid":this.data.saler_hrid,//销售人员hrid,业务员hrid
          "signbackstatus":this.signbackstatus,
          "tradefieldmx":this.data.tradefieldmx,
          "pay_enterpriseid":this.data.pay_enterpriseid,
          "tradefield":this.data.tradefield,
          "saletype":this.saletype,
          "rebate_used":this.checked,//默认0，是否使用返利金
          "signbacknum":'',
          "sa_promotionid":this.data.sa_promotionid,
          "billdate":this.billdate
        },
      })
      this.tool.showMessage(res,()=>{
        this.$emit('onSuccess')
        if (this.data.type === '标准订单' ||  this.data.type === '特殊订单') {
          this.isusedrebate === 1?this.useRebate():""
        }
        
        this.drawer = false
      })
    },
    onEditSuccess () {
      this.$refs.addpro.listData()
    },
    addMoreProduct () {
      this.setcol === 12?this.setcol = 24 : this.setcol = 12
    },
    // 订单添加商品
    async onConfirm (data) {
      const res = await this.$api.requested({
        "id": 20221109093602,
        "content": {
          "sa_orderid": this.$route.query.id, //订单ID
          "sys_enterpriseid": this.data.sys_enterpriseid, //企业ID
          "type":this.data.type, //订单类型
          "items": data.map(e=>{
            return {
              sa_orderitemsid:0,
              itemid:e.itemid,
              qty:e.orderminqty,
              needdate:e.deliverydate
            }
          })
        },
      })
      this.tool.showMessage(res,()=>{
        this.setcol = 24
        this.$refs['prolist'].listData()
        // this.$emit('onSuccess')
      })
    },
    async useRebate () {
      let that = this
      if (this.rebateamount > this.defaultData.rebatebalance ||this.rebateamount > (this.data.amount * this.data.order_rebate_userate / 100) ) return  this.$message({
        message:`余额不足或已超过可用上限!`,
        type:function () {
          that.rebateamount = 0
          return 'error'
        }()
      })
      if (this.rebateamount == null) return this.$message({
          message:"返利金不能为空",
          type:'error'
        })
      const res = await this.$api.requested({
        "id": 20230218225002,
        "content": {
          "sa_orderid": this.data.sa_orderid, //订单金额
          "isused": this.checked, //是否使用
          "rebateamount": this.rebateamount //返利金使用金额
        },
      })
      if (res.code === 0) this.$message({
        message:`使用返利金失败!${res.msg}`,
        type:'error'
      })
    },
    // 查询站点是否使用返利金
    async queryUsedrebate () {
      const res = await this.$api.requested({
         "classname": "webmanage.site.site",
        "method": "querySite_Parameter",
        "content": {
        }
      })
      this.isusedrebate = res.data.order_rebate_used
    },
    // 选择结算企业
    onSelect (data) {
      this.financiallist = data.finance
      data.finance.forEach(e => {
        if (e.isdefault === 1) {
           this.defaultData.fin_info = e
        } else {
          this.defaultData.fin_info = data.finance.length > 0 ?data.finance[0]:{}
        }
      });
    },

    async selectOptions () {
      const res = await this.$store.dispatch('optiontypeselect','saletype')
      this.saleroptions = res.data
    },

    async selectRow (data) {
      this.saler_name = data.name
      const res = await this.$api.requested({
        "id": 20230213154802,
        "content": {
          "saler_hrid": data.hrid,
          "sa_orderid": this.data.sa_orderid
        },
      })
      this.$refs['saler'].visible = false
    }
  },
}

</script>
<style>
</style>
<style scoped>
.reveive__panel{
  font-size: 16px;
  line-height: 30px;
  padding: 10px;
  background: #d9ecff;
  border: 1px dashed #0676e7;
}
.account__panel small,.reveive__panel small{
  color:#888
}
.account__panel{
  width: calc(25% - 26px);
  padding: 10px;
  margin-bottom:10px;
  border: 1px dashed #666;
}
.act{
  background: #d9ecff;
  border: 1px dashed #0676e7;
}
.image {
  width:40px;height:40px;margin:0px auto;
}
.order__note__input{
  border: none;
  outline: none;
  /* margin-left: 10px; */
  /* border-bottom: 1px solid #f1f2f3; */
  flex:1
}
</style>