<template>
  <div class="salesNewEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" @back="handleBack" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="salesEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ detailData&&detailData.salesBillNo }}</span>
          <span v-if="detailData&&detailData.salesBillNoSource">（原：{{ detailData&&detailData.salesBillNoSource || '--' }}）</span>
          <span style="margin-left:15px;color:#00aaff;cursor:pointer;"  @click="showDetail=!showDetail">
            <a-icon title="查看信息" type="eye"/> 查看信息
          </span>
        </template>
      </a-page-header>
      <!-- 单据详情 -->
      <a-card size="small" :bordered="false" class="salesEdit-cont" v-show="showDetail">
        <div style="padding: 10px;">
          <a-descriptions size="small" :column="3">
            <a-descriptions-item label="客户名称">{{ detailData&&detailData.buyerName || '--' }}</a-descriptions-item>
            <a-descriptions-item label="收货地址" :span="2">{{ shippingAddress||'--' }}</a-descriptions-item>
            <a-descriptions-item label="收货人">{{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.consigneeName || '--' }}</a-descriptions-item>
            <a-descriptions-item label="收货电话">{{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.consigneeTel || '--' }}</a-descriptions-item>
            <a-descriptions-item label="收款方式">{{ detailData&&detailData.settleStyleSnDictValue || '--' }}</a-descriptions-item>
            <a-descriptions-item label="审核时间">{{ detailData&&detailData.auditDate || '--' }}</a-descriptions-item>
            <a-descriptions-item label="业务状态">{{ detailData&&detailData.billStatusDictValue || '--' }}</a-descriptions-item>
            <a-descriptions-item label="财务状态">{{ detailData&&detailData.financialStatusDictValue || '--' }}</a-descriptions-item>
            <a-descriptions-item label="备注" :span="3">{{ detailData&&detailData.remarks || '--' }}</a-descriptions-item>
          </a-descriptions>
        </div>
      </a-card>
      <!-- 正常产品 -->
      <a-card size="small" :bordered="false" class="salesEdit-cont" v-if="salesBillSn">
        <div style="padding: 10px;">
          <productNormalList 
          ref="productNormalList" 
          @openCpModal="openProductModal" 
          :detailData="detailData" 
          :warehouseSn="warehouseSn" 
          :salesBillSn="salesBillSn"></productNormalList>
        </div>
      </a-card>
      <!-- 活动产品 -->
      <a-card 
      size="small" 
      :bordered="false" 
      class="salesEdit-cont" 
      v-for="item in activeList" 
      :key="item.promoRuleSn" 
      >
        <div slot="title" style="display: inline-block;width:100%;">
          <strong style="margin-right:10px;font-size:14px;">{{item.promotion.title}}</strong> ({{item.promotionRule.description}})
          <span style="margin-left:20px;color:#00aaff;cursor: pointer;"  @click="(event) => {showDesc(event, item)}">
            <a-icon title="查看活动详情" type="eye"/> 活动详情
          </span>
          <span style="margin:0 20px;color:#ff0800;cursor: pointer;" @click="(event) => {disabledActive(event, item)}">
            <a-icon title="禁用规则" type="disconnect"/> 禁用规则
          </span>
        </div>
        <div slot="extra" @click="tooglePanel(item)" style="cursor: pointer;">{{ item.isActive ? '收起' : '展开' }} <a-icon type="caret-right" :rotate="item.isActive ? 90 : 0"/> </div>
        <div v-show="item.isActive" style="padding: 10px;">
          <productList 
          :ref="'productList-'+item.promoRuleSn" 
          :id="item.promoRuleSn" 
          @openCpModal="openProductModal" 
          @insterOk="insterActiveOk"
          :promo="item"
          :detailData="detailData" 
          :warehouseSn="warehouseSn" 
          :salesBillSn="salesBillSn"></productList>
        </div>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <div class="footer-price">
        <div></div>
        <div>
          <div class="totalPrice">合计：￥<span>121.60</span></div>
          <div>
            产品总款数：<strong>12</strong>；
            总数量：<strong>111</strong>；
            总售价：<strong>17898.88</strong>；
            <span style="margin-right:10px;">优惠金额：<strong>121.60</strong></span>
            <a-popover title="优惠明细">
              <a-button shape="round" size="small">优惠明细</a-button>
              <div slot="content">
                <div class="yhdetail" style="min-width:300px;">
                  <div class="yhdetail-h" style="font-weight: bold;font-size:14px;">520以爱之名保护你</div>
                  <div style="padding-left:10px;">
                    <div>卖产品送产品：￥<strong>220</strong></div>
                    <div class="yhdetail-d" style="color:#999;">满10送2</div>
                  </div>
                </div>
                <div class="yhdetail">
                  <div class="yhdetail-h" style="font-weight: bold;font-size:14px;">滤清器夏季大派送</div>
                  <div style="padding-left:10px;">
                    <div>卖产品送产品：￥<strong>220</strong></div>
                    <div class="yhdetail-d" style="color:#999;">满10送2</div>
                  </div>
                </div>
                <div class="yhdetail">
                  <div class="yhdetail-h" style="font-weight: bold;font-size:14px;">520以爱之名保护你</div>
                  <div style="padding-left:10px;">
                    <div>卖产品送产品：￥<strong>220</strong></div>
                    <div class="yhdetail-d" style="color:#999;">满10送2</div>
                  </div>
                </div>
              </div>
            </a-popover>
          </div>
        </div>
      </div>
      <div>
        <a-button
          size="large"
          style="padding: 0 60px;"
          :disabled="spinning"
          type="primary"
          class="button-primary"
          @click="handleSubmit()"
          id="productInfoList-handleSubmit">提交</a-button>
      </div>
    </div>
    <!-- 添加产品 -->
    <chooseProduct
        ref="chooseProduct"
        :openModal="showCpModal"
        @close="closeProductModal"
        @addProduct="insterProduct"></chooseProduct>
    <!-- 价格更新弹窗 -->
    <setPriceModal :show="priceUpdateModal" :totalRealAmount="updataData.totalRealAmount" :totalAmount="updataData.totalAmount" @ok="updatePrice" @cancel="priceUpdateModal=false"></setPriceModal>
 </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import productList from './comps/productList.vue'
import productNormalList from './comps/productNormalList.vue'
import chooseProduct from './comps/chooseProduct.vue'
import setPriceModal from './setPriceModal.vue'
import { salesDisablePromo } from '@/api/salesDetailNew'
import { salesDetailBySn, salesWriteSubmit, submitCheck, updateBatch, salesPromoQueryList, salesQueryUnPartPromo } from '@/api/salesNew'
export default {
  name: 'SalesNewEdit',
  mixins: [commonMixin],
  components:{
    setPriceModal,
    productList,
    chooseProduct,
    productNormalList
  },
  data () {
    return {
      spinning: false,
      activeList:[], // 活动列表
      activeDesKey: {},
      salesBillSn: null, // 销售单sn
      detailData: { discountAmount: 0, id: null, salesBillSn: '' }, // 订单基础数据
      warehouseSn: undefined,
      updataData: {
        totalRealAmount: '',
        totalAmount: ''
      },
      priceUpdateModal: false, // 价格更新弹窗
      showDetail: false,
      showCpModal: false,
      cpCurRefId: '',
      disabledActiveOption: null
    }
  },
  computed: {
    shippingAddress () {
      const shippingAddrProvinceName = this.detailData && this.detailData.salesBillExtEntity && this.detailData.salesBillExtEntity.shippingAddrProvinceName ? this.detailData.salesBillExtEntity.shippingAddrProvinceName : ''
      const shippingAddrCityName = this.detailData && this.detailData.salesBillExtEntity && this.detailData.salesBillExtEntity.shippingAddrCityName ? this.detailData.salesBillExtEntity.shippingAddrCityName : ''
      const shippingAddrCountyName = this.detailData && this.detailData.salesBillExtEntity && this.detailData.salesBillExtEntity.shippingAddrCountyName ? this.detailData.salesBillExtEntity.shippingAddrCountyName : ''
      const shippingAddr = this.detailData && this.detailData.salesBillExtEntity && this.detailData.salesBillExtEntity.shippingAddr ? this.detailData.salesBillExtEntity.shippingAddr : ''
      if (!shippingAddrProvinceName && !shippingAddrCityName && !shippingAddrCountyName && !shippingAddr) {
        return '--'
      } else {
        return shippingAddrProvinceName + shippingAddrCityName + shippingAddrCountyName + shippingAddr
      }
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryNewList', query: { closeLastOldTab: true } })
    },
    tooglePanel(item){
      item.isActive=!item.isActive
      this.activeList.splice()
    },
    //  销售单详情
    getOrderDetail (flag) {
      salesDetailBySn({ salesBillSn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
        }
        this.getActiveList()
      })
    },
    // 获取销售单参与的活动列表
    async getActiveList(){
      const hasNewActive = await salesQueryUnPartPromo({ salesBillSn: this.$route.params.sn }).then(res => res.data)
      console.log(hasNewActive)
      // 有新活动
      if(hasNewActive.length){
        this.showNewActiveModal(hasNewActive)
      }
      this.activeList = await salesPromoQueryList({ salesBillSn: this.$route.params.sn }).then(res => res.data || [])
      this.activeList.map(item => {
        item.isActive = true
        this.activeDesKey['search-'+item.promoRuleSn] = false
      })
    },
    // 新活动确认弹框
    showNewActiveModal(data){
      let arr = []
      data.map(item => {
        arr.push(item.title)
      })
      this.$confirm({
        title: '新活动提醒',
        centered: true,
        class:'confirm-center',
        content: <div>
          <div style="padding:10px 0;text-align:center;">
            系统发布新的促销活动：
          </div>
          <div style="text-align:center;color:#00aaff;">{arr.join('，')}</div>
          <div style="padding:10px 0;text-align:center;">
            是否将现有产品识别到新的活动中吗？
          </div>
        </div>,
        onOk() {
           
        },
        onCancel() {},
      });
    },
    // 添加产品，包括正常和活动的产品
    closeProductModal(){
        this.cpCurRefId = ''
        this.showCpModal = false
    },
    // 打开选择产品弹框
    openProductModal(type, refId){
        console.log(type, refId)
        const promo = this.activeList.find(item => item.promoRuleSn == refId)
        this.$refs.chooseProduct.pageInit(this.detailData, promo, type)
        this.cpCurRefId = 'productList-' + refId
        this.showCpModal = true
    },
    // 添加活动产品成功的回调
    insterActiveOk(){
      // 刷新正常产品列表
      this.$refs.productNormalList.resetSearchForm()
    },
    // 新增产品
    insterProduct(row, promotionFlag, type){
      // 正常产品
      if(type == 0){
        this.$refs.productNormalList.insterProduct(row, promotionFlag)
      }else{
        // 活动产品
        this.$refs[this.cpCurRefId][0].insterProduct(row, promotionFlag, type)
      }
    },
    // 选择价格类型  并更新
    updatePrice (type) {
      const _this = this
      if (type == 0) {
        const ajax_data = {
          salesBillSn: _this.salesBillSn,
          productPriceChangeFlag: type
        }
        _this.submitResult(ajax_data)
      } else {
        updateBatch(_this.updataData.detailList).then(res => {
          if (res.status == 200) {
            const ajax_data = {
              salesBillSn: _this.salesBillSn,
              productPriceChangeFlag: type
            }
            _this.submitResult(ajax_data)
          }
        })
      }
    },
    // 提交销售单
    handleSubmit () {
      // 先不提交,先判断是否有价格更新  （下级创建时判断）
      if (this.detailData && this.detailData.salesBillSource && this.detailData.salesBillSource == 'PURCHASE') {
        submitCheck({ salesBillSn: this.salesBillSn }).then(res => {
          if (res.status == 200) {
            if (res.data.detailList.length > 0) {
              this.updataData = res.data
              const _this = this
              this.$nextTick(() => {
                _this.priceUpdateModal = true
              })
            } else {
              const ajax_data = { salesBillSn: this.salesBillSn }
              this.submitResult(ajax_data)
            }
          }
        })
      } else {
        const ajax_data = { salesBillSn: this.salesBillSn }
        this.submitResult(ajax_data)
      }
    },
    // 提交
    submitResult (data) {
      this.spinning = true
      salesWriteSubmit(data).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 展开收缩活动详情
    showDesc(e,item){
      e.stopPropagation()
      const row = this.$refs['productList-'+item.promoRuleSn][0]
      row&&row.showDesc(item.promotionRule)
    },
    // 禁用活动
    disabledActive(e,item){
      const _this = this
      if(item.disabled){
        this.$message.info("规则已经禁用!")
        return
      }
      this.$confirm({
        title: '确定禁用规则?',
        centered: true,
        class:'confirm-center',
        content: <div>
          <div style="padding:10px 0;text-align:center;">禁用规则后，将无法享受该活动规则优惠</div>
          <div style="padding:0 0 10px 0;text-align:center;">
            <aRadioGroup onChange={_this.changeDaOpt}>
              <aRadio style="display:block;height: '30px';lineHeight: '30px';padding:5px 0;" value="DELETE">
                删除规则中相关产品
              </aRadio>
              <aRadio style="display:block;height: '30px';lineHeight: '30px';padding:5px 0;" value="REMOVE">
                移出规则中相关产品
              </aRadio>
            </aRadioGroup>
          </div>
        </div>,
        onOk() {
          if(_this.disabledActiveOption){
            salesDisablePromo({
              salesBillSn: _this.salesBillSn,
              salesPromoSn: item.salesPromoSn,
              promoRuleSn: item.promoRuleSn,
              salesDisableType: _this.disabledActiveOption
            }).then(res => {
              if(res.status == 200){
                _this.$refs['productList-'+item.promoRuleSn][0].disableActive()
                _this.disabledActiveOption = null
                item.disabled = true
              }
            })
          }else{
            _this.$message.info("请选择如何禁用规则!")
            return true
          }
        },
        onCancel() {
          _this.disabledActiveOption = null
        },
      });
    },
    changeDaOpt(e){
      console.log(e)
      this.disabledActiveOption = e.target.value
    },
    pageInit () {
      this.salesBillSn = this.$route.params.sn
      this.warehouseSn = this.$route.params.sn ? this.$route.params.wSn : ''
      this.getOrderDetail(true)
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .salesNewEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 75px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
    .salesEdit-cont{
      margin: 10px 0;
    }
    .redStyle{
      font-weight: bold;
      color: red;
    }
    .ellipsisCon{
      display: flex;
      justify-content: space-between;
      align-items: center;
      .ellipsisText{
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        display: box;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
    }
    .ant-card-small > .ant-card-body {
        padding: 0!important;
    }
    .affix-cont{
      padding: 10px 15px;
      text-align: right;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .footer-price{
        flex-grow:1;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        > div{
          padding: 0 15px;
        }
        .totalPrice{
          span{
            font-weight: bold;
            color: red;
            font-size: 20px;
          }
        }
      }
    }
  }

</style>
