<template>
  <div>
    <!-- <el-button :disabled="data.status !=='新建'" type="primary" size="mini" @click="onShow(drawer = true)">编 辑</el-button> -->
    <el-button type="primary" :disabled="data.type === '特殊订单'" 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.defaultamount,2)}}</b></span></p>
      </div>
      <div class="flex-align-center">
        <p v-if="freefreightamount" style="font-size: 13px !important;color: #8888;font-weight: normal">{{checkFreefreightamount}}</p>
      </div>
    </div>
    <div class="drawer__panel">
      <!-- 项目订单显示信息 -->
      <div v-if="data.type === '项目订单'" class="reveive__panel normal-margin flex-align-center">
        <p class="inline-16"><small>项目信息:</small>{{data.projectname}}</p>
        <p class="inline-16"><small>合同信息:</small>{{data.contract_title}}</p>
        <p class="inline-16"><small>领域:</small>{{data.tradefield}}</p>
        <p class="inline-16"><small>品牌:</small>{{data.brandname}}</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 !== '项目订单'" @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>{{data.rebate_used ? tool.formatAmount(data.defaultamount - rebateamount,2) : data.defaultamount}}</p>
          </div>
          <div v-if="(data.type === '标准订单' ||  data.type === '特殊订单') && isusedrebate === 1">
            <el-checkbox v-model="checked" :true-label="1" :false-label="0" @change="rebateUsedChange">使用返利金</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="data.rebateamount" @blur="useRebate(data.rebateamount)" placeholder="输入使用金额"></el-input>
              <small>(返利金最高使用比例{{data.order_rebate_userate}})</small>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-align-center 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">
              <addAmountInfo style="text-align:right" :data="{sys_enterpriseid:data.sys_enterpriseid}" @onSuccess="thisDetail().queryMainData().then(() => {setDefaultData()})"/>
              <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>
            <div class="flex-align-center">
              <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>
        <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">
              <div class="flex-align-center" style="justify-content:space-between;margin-bottom:10px">
                <el-input 
                  size="small"  
                  v-model="addressparam.content.where.condition" 
                  placeholder="请输入搜索内容" 
                  style="width:150px"
                  @keyup.enter.native="receiveAddress(addressparam.content.pageNumber = 1)" @clear="receiveAddress(addressparam.content.pageNumber = 1)" clearable></el-input>&nbsp;
                <addAddressInfo style="text-align:right" @onAddSuccess="receiveAddress()" :mainData="{sys_enterpriseid:data.sys_enterpriseid}"/>
              </div>
              <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>
              <div class="container" style="text-align:right">
                <el-pagination
                  background
                  small
                  :current-page="addressparam.content.pageNumber"
                  @current-change="addresPageChange"
                  layout="total,prev, pager, next"
                  :total="addresstotal">
                </el-pagination>
              </div>
              <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.remarks"
              :value="item.value">
            </el-option>
          </el-select>
        </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="normal-margin" v-if="data.type === '标准订单' || data.type === '特殊订单'">
        <p class="normal-title mt-10 inline-16">项目备注</p>
        <el-input size="mini" class="order__note__input" type="textarea" v-model="data.projectnote" :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 './productlist.vue'
import addProduct from '@/template/orderCanUseProduct/index.vue'
import financeEnterprise from '@/template/orderCanUseFinance/index.vue'
import addAmountInfo from '@/components/financialInfo/modules/add'
import addAddressInfo from '@/HManagement/marketing2/agent/details/modules/address/add'
export default {
  props:['data'],
  components:{
    previewImage,
    productList,
    addProduct,
    financeEnterprise,
    addAmountInfo,
    addAddressInfo
  },
  inject:['thisDetail'],
  computed:{
    checkFreefreightamount () {
      let result = ''
      switch (this.freefreightamount) {
        case -1:
          result = '不免运费'
          break;
        case 0:
          result = '免运费'
          break;
        default:
          result = this.data.amount >= this.freefreightamount?'当前订单免运费':`订单满${this.tool.formatAmount(this.freefreightamount,2)}元免运费,当前还差${this.tool.formatAmount(this.freefreightamount - this.data.amount,2)}元`
          break;
      }
      return result
    },
  },
  data () {
    return {
      freefreightamount:'',
      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:"",
      freefreightamount:'',
      addressparam: {
        "id": "20221009155803",
        "content": {
          "nocache":true,
          "pageNumber":1,
          "pageSize":10,
          "sys_enterpriseid":'',
          "where":{
            "condition":"",
            "workaddress":1
          }
        }
      },
      addresstotal:0
    }
  },
  created () {
    this.queryBasicInfo()
  },
  methods:{
    addresPageChange (n) {
      this.addressparam.content.pageNumber = n
      this.receiveAddress()
    },
    async queryBasicInfo () {
      const res = await this.$api.requested({
        "id":20220920084001,"content":{
          sys_enterpriseid:this.data.sys_enterpriseid
        },
      })
      this.freefreightamount = res.data.freefreightamount
    },
    async rebateUsedChange(){
      console.log(this.data)
      if(this.data.status != '新建') return false
      let amount = this.data.order_rebate_userate * this.data.defaultamount; //最大可用金额
      let rebatebalance = this.data.rebatebalance; //返利金账户余额
      const res = await this.$api.requested({
        "id": 20230218225002,
        "content": {
          "sa_orderid": this.data.sa_orderid, //订单金额
          "isused": this.checked, //是否使用
          "rebateamount": rebatebalance > amount ? amount : rebatebalance //返利金使用金额
        }
      })
      this.$emit('onSuccess')
      // this.data.rebate_used = res.msg !== '成功' ? this.data.rebate_used == 0?1:0:this.data.rebate_used
    },
    onShow () {
      this.initPage()
    },
    async initPage () {

      this.setDefaultData()

      this.receiveAddress()

      this.queryUsedrebate()

      this.selectOptions()

      this.checked = this.data.rebate_used
      if (this.data.rebateamount > this.data.defaultamount) {
        this.rebateamount = this.tool.formatAmount(+this.data.defaultamount / 2)
      } else {
        this.rebateamount = this.data.rebateamount
      }
    },
    // 收货信息:合作企业联系人
    async receiveAddress (fn) {
      this.addressparam.content.sys_enterpriseid = this.data.sys_enterpriseid
      const res = await this.$api.requested(this.addressparam)
      this.addresstotal = res.total
      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
    },
   
    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.data.billdate,
          "projectnote":this.data.projectnote
        },
      })
      this.tool.showMessage(res,()=>{
        this.$emit('onSuccess')
        /*if (this.data.type === '标准订单' ||  this.data.type === '特殊订单') {
          this.isusedrebate === 1?this.useRebate(this.data.rebateamount):""
        }*/
      })
    },
    onEditSuccess () {
      this.$refs.prolist.listData()
      this.$emit('onSuccess')
    },
    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": "标准订单", //订单类型
          "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 (e) {
      let that = this
      /* 修改返利金 */
      let rebateamount = e;
      let amount = this.data.order_rebate_userate * this.data.defaultamount;//最大可用金额
      const res = await this.$api.requested({
        "id":20230218225002,
        "content":{
          "sa_orderid":this.data.sa_orderid,//订单金额
          "isused":1,//是否使用
          "rebateamount":rebateamount>amount?amount:rebateamount
          }
        })
      if(res.data=='成功'){
        this.$emit('onSuccess')
        this.initPage()
        if(rebateamount>amount){
          this.data.rebateamount=amount
          this.$message({
            message: '返利金最大可用值'+ amount,
            type: 'warning'
          });
        }
      }else{
        this.$message.error(res.msg);
      }
    },
    // 查询站点是否使用返利金
    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.defaultData.finance = 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
    }
  },
}

</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>