<template>
  <q-card class="q-px-md" style="width:800px;max-width:800px;">
    <q-card-section class="row items-center q-pb-none">
      <div class="text-h6">{{model.Id==0?"创建报价单":"修改报价单"}}</div>
      <q-space />
      <q-btn icon="close" flat round dense v-close-popup />
    </q-card-section>
    <q-card-section style="max-height:75vh;" class="scroll">
      <q-banner rounded class="bg-orange-2 text-black q-py-none q-px-md q-mb-md" style="min-height:30px;">
        <div class="row items-center">
          <span class="q-mr-md">
            <inline-svg class="svg-icon svg-icon-orange" src="icons/svg/Code/Warning-2.svg"></inline-svg>
          </span>
          <span style="font-size:12px;">报价单价格系统将进行自动计算，如需额外的优惠请创建报价单后进行申请</span>
        </div>
      </q-banner>
      <div class="row" style="margin-bottom:10px;">
        <div class="col q-mr-md">
          <q-input standout bottom-slots v-model="model.Name" filled ref="Name" label="报价单名称" dense />
        </div>
        <div class="col">
          <q-select dense standout behavior="menu" filled v-model="model.CustomerSource" ref="CustomerSource"
            :options="CustomerSources" option-label="name" option-value="id" label="客户来源" emit-value map-options
            :rules="[val => !!val || '请选择客户来源']" />
        </div>
      </div>
      <div class="row" style="margin-bottom:10px;">
        <div class="col q-mr-md">
          <q-select dense standout behavior="menu" filled v-model="model.CustomerType" ref="CustomerType"
            :options="CustomerTypes" option-label="name" option-value="id" label="客户类型" emit-value map-options
            @input="changeDiscountMoney" :rules="[val => !!val || '请选择客户类型']" />
        </div>
        <div class="col">
          <q-input standout bottom-slots filled v-model="model.JoinNum" ref="JoinNum" label="报名人数" dense mask="#"
            fill-mask="0" reverse-fill-mask :rules="[val => !!val || '请输入报名人数']" @input="changeDiscountMoney">
            <template v-slot:append>
              <span style="font-size:14px;">人</span>
            </template>
          </q-input>
        </div>
      </div>
      <div class="row" style="margin-bottom:10px;">
        <div class="col q-mr-md">
          <q-input standout bottom-slots filled v-model="model.CustomerName" ref="CustomerName" label="客户姓名" dense
            :rules="[val => !!val || '请输入客户姓名']" />
        </div>
        <div class="col">
          <q-input standout bottom-slots filled v-model="model.CustomerTel" label="客户电话" dense mask="#"
            reverse-fill-mask />
        </div>
      </div>
      <div class="text-subtitle2 text-weight-bold q-mb-md">
        <span>选择课程</span>
      </div>
      <div class="row">
        <div class="col-3">
          <q-select @input="getCourses" dense standout behavior="menu" class="q-mr-md" filled v-model="msg.CourseSubject" :options="CourseSubjectList"
            option-label="SubjectName" option-value="Id" emit-value map-options label="所属科目" clearable />
        </div>
        <div class="col">
          <q-select dense standout behavior="menu" filled v-model="chosenCourse" :options="courseOptions"
            @filter="filterCourseFn" input-debounce="0" use-input option-label="CourseName" option-value="CourseId"
            emit-value map-options :placeholder="!chosenCourse ? '添加客户需要的课程' : ''" clearable />
        </div>
        <div class="q-ml-md">
          <q-btn color="primary" label="添加" @click="addCourse"></q-btn>
        </div>
      </div>
      <div class="q-mt-md">
        <q-table :pagination="pageInfo" no-data-label="暂无相关数据" flat
          class="sticky-column-table sticky-header-table sticky-right-column-table no-bottom-table" separator="none"
          :data="chosenCourses" :columns="columns" row-key="name">
          <template v-slot:body-cell-DiscountRemark="props">
            <q-td :props="props" class="text-negative">
              <div v-for="(x, i) in props.value.split('^')" style="border-bottom:1px dotted #f5f6f7;">
                {{ x }}
              </div>
            </q-td>
          </template>
          <template v-slot:bottom>
            <div>&nbsp;</div>
          </template>
        </q-table>
      </div>
      <div style="border-top:1px solid #f5f6f7;" class="row q-py-md">
        <div class="col">
          <span>累计优惠：</span>
          <span class="q-ml-xs text-weight-bold">￥{{
              model.TotalPrice ? model.TotalDiscountPrice.toFixed(2) : "0.00"
            }}</span>
        </div>
        <div class="col  text-right">
          <span>课程总价：</span>
          <span class="q-ml-xs text-weight-bold">￥{{
              model.TotalPrice ? model.TotalPrice.toFixed(2) : "0.00"
            }}</span>
        </div>
      </div>
      <div class="row">
        <div class="col q-mr-md"></div>
        <div class="col">
          <q-input standout bottom-slots filled v-model="model.EffectiveEnd" ref="EffectiveEnd" label="报价有效期" dense
            mask="date" class="cursor-pointer" readonly :rules="[val => !!val || '请选择有效日期']">
            <template v-slot:append>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy>
                  <q-date v-model="model.EffectiveEnd" title="" subtitle="报价有效日期">
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="确认" color="primary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>
      </div>
    </q-card-section>
    <q-card-actions align="right" class="bg-white">
      <q-btn label="取消" flat color="primary" v-close-popup />
      <q-btn :label="model.Id==0?'创建报价单':'保存报价单'" color="accent" class="q-px-md" style="font-weight:400 !important"
        @click="saveOffice" />
    </q-card-actions>
  </q-card>
</template>

<script>
  import {
    queryCourseDropdownList,
    saveCourseOffer,
    queryCourseOfferInfo,
    getCourseSubject
  } from "../../api/course/index";
  import {
    date
  } from "quasar";
  export default {
    props: ["obj"],
    data() {
      return {
        CustomerTypes: [{
            id: 1,
            name: "新客户"
          },
          {
            id: 2,
            name: "续班客户"
          }
        ],
        CustomerSources: [{
            id: 1,
            name: "学校介绍"
          },
          {
            id: 2,
            name: "朋友介绍"
          },
          {
            id: 3,
            name: "网络广告"
          }
        ],
        model: {},
        columns: [{
            name: "CourseName",
            required: true,
            label: "课程名称",
            align: "left",
            field: row => row.CourseName
          },
          {
            name: "OriginalPrice",
            required: true,
            label: "现价",
            align: "left",
            field: row => row.OriginalPrice.toFixed(2)
          },
          {
            name: "JoinNum",
            required: true,
            label: "报名人数",
            align: "left",
            field: row => row.JoinNum
          },
          {
            name: "DiscountPrice",
            required: true,
            label: "优惠",
            align: "left",
            field: row => row.DiscountPrice.toFixed(2)
          },
          {
            name: "DiscountRemark",
            required: true,
            label: "优惠说明",
            align: "left",
            field: row => row.Remark
          },
          {
            name: "ActualPrice",
            required: true,
            label: "小计金额",
            align: "left",
            field: row => row.ActualPrice.toFixed(2)
          }
        ],
        pageInfo: {
          pageIndex: 1,
          pageSize: 12,
          rowsPerPage: 12
        },
        msg: {
          CourseSubject: "", //所属科目
        },
        courseList: [], //课程列表
        courseOptions: [],
        chosenCategory: null, //选中的系列
        chosenCourse: null, //选中的课程
        chosenCourses: [],
        CourseSubjectList: [], //科目列表
      };
    },
    computed: {

    },
    created() {
      this.queryCourseSubject();
      this.getCourses();
    },
    mounted() {
      this.initObj();
    },
    methods: {
      queryCourseSubject() {
        getCourseSubject({}).then(res => {
          if (res.Code == 1) {
            this.CourseSubjectList = res.Data;
          }
        })
      },
      //初始化对象
      initObj() {
        if (this.obj && this.obj.Id > 0) {
          queryCourseOfferInfo({
            Id: this.obj.Id
          }).then(res => {
            var tempObj = res.Data;
            if (res.Code == 1) {
              this.model = {
                Id: tempObj.Id,
                Name: tempObj.Name,
                EffectiveStart: tempObj.EffectiveStart,
                EffectiveEnd: tempObj.EffectiveEnd,
                CustomerType: tempObj.CustomerType,
                CustomerSource: tempObj.CustomerSource,
                TotalOriginalPrice: tempObj.TotalOriginalPrice,
                TotalPrice: tempObj.TotalPrice,
                TotalDiscountPrice: tempObj.TotalDiscountPrice,
                CustomerInfo: tempObj.CustomerInfo,
                CustomerName: tempObj.CustomerName,
                CustomerTel: tempObj.CustomerTel,
                OfferDetails: [],
                JoinNum: tempObj.JoinNum,
                OfferType: tempObj.OfferType, //课程
              };
              if (tempObj.OfferDetails && tempObj.OfferDetails.length > 0) {
                this.model.OfferDetails = tempObj.OfferDetails;
                this.chosenCourses = tempObj.OfferDetails
              }
            }
          })
        } else {
          this.model = {
            Id: 0,
            Name: "",
            OfferType: 1, //课程
            EffectiveStart: "",
            EffectiveEnd: "",
            CustomerType: null,
            CustomerSource: null,
            TotalOriginalPrice: 0.0,
            TotalPrice: 0.0,
            TotalDiscountPrice: 0.0,
            CustomerInfo: "",
            CustomerName: "",
            CustomerTel: "",
            OfferDetails: [],
            JoinNum: 0
          };
        }
      },
      //保存报价单
      saveOffice() {
        this.$refs.EffectiveEnd.validate();
        this.$refs.CustomerType.validate();
        this.$refs.CustomerSource.validate();
        this.$refs.CustomerName.validate();
        this.$refs.JoinNum.validate();
        if (
          !this.$refs.EffectiveEnd.hasError &&
          !this.$refs.CustomerType.hasError &&
          !this.$refs.CustomerSource.hasError &&
          !this.$refs.CustomerName.hasError &&
          !this.$refs.JoinNum.hasError &&
          this.chosenCourses.length > 0
        ) {
          this.model.EffectiveStart = date.formatDate(Date.now(), "YYYY/MM/DD");
          if (this.model.Name == "") {
            this.model.Name = `${this.model.CustomerName}${date.formatDate(
            Date.now(),
            "YYYYMMDDHHmmss"
          )}报价单`;
          }
          this.model.OfferDetails = this.chosenCourses;
          saveCourseOffer(this.model).then(r => {
            this.$q.notify({
              icon: "iconfont icon-chenggong",
              color: "positive",
              timeout: 2000,
              message: "报价单保存成功",
              position: "top",
              actions: [{
                label: "点击查看",
                color: "primary",
                handler: () => {
                  this.$router.push({
                    path: "/sale/quotation",
                    query: {
                      Id: r.Data
                    }
                  });
                }
              }]
            });
            this.$emit("save");
          });
        }
      },
      //获取课程列表
      getCourses() {
        this.courseList = [];
        var qMsg = {
          CourseName: "",
          CateId: 0,
          IsQPrice: 1,
          CourseSubject: this.msg.CourseSubject,
        };
        this.chosenCourse = null;
        queryCourseDropdownList(qMsg).then(res => {
          this.courseList = res.Data;
          this.courseOptions = this.courseList;
        });
      },
      //课程筛选
      filterCourseFn(val, update, abort) {
        update(() => {
          this.courseOptions = this.courseList.filter(
            v => v.CourseName.indexOf(val) > -1
          );
        });
      },
      //添加课程
      addCourse() {
        this.$refs.JoinNum.validate();
        this.$refs.CustomerType.validate();
        if (!this.$refs.JoinNum.hasError && !this.$refs.CustomerType.hasError) {
          let val = this.courseList.find(x => x.CourseId == this.chosenCourse);
          if (val) {
            let temp = this.chosenCourses.find(x => x.CourseId == val.CourseId);
            if (!temp) {
              let offer = this.genernalOffer(val);
              if (this.chosenCourses.length > 0) {
                offer.DiscountPrice += 500;
                if (offer.OriginalPrice > 5000) {
                  offer.ActualPrice -= 500;
                  offer.Remark += `^购买多项课程再减500`;
                }
              }
              this.chosenCourses.push(offer);
              this.SumMoney();
            }
          }
        }
      },
      changeDiscountMoney() {
        this.chosenCourses.forEach((x, i) => {
          x.ActualPrice = x.SourceData.SellPrice * this.model.JoinNum;
          x.JoinNum = this.model.JoinNum;
          this.formatDiscount(x.SourceData, x);
          if (i > 0) {
            x.DiscountPrice += 500;
            x.ActualPrice -= 500;
            x.Remark += `^购买多项课程再减500`;
          }
        });
        this.SumMoney();
      },
      SumMoney() {
        let dis = 0.0,
          total = 0.0;
        this.chosenCourses.forEach(x => {
          dis += parseFloat(x.DiscountPrice);
          total += parseFloat(x.ActualPrice);
        });
        this.model.TotalDiscountPrice = dis;
        this.model.TotalPrice = total;
        this.model.TotalOriginalPrice = dis + total;
      },
      genernalOffer(val) {
        let offer = {
          DetailsId: 0,
          OfferId: 0,
          CourseId: val.CourseId,
          CourseName: val.CourseName,
          OriginalPrice: val.SellPrice,
          DiscountPrice: 0,
          ActualPrice: val.SellPrice * this.model.JoinNum,
          ClassHours: val.ClassHours,
          Remark: "",
          JoinNum: this.model.JoinNum
        };
        offer.SourceData = val;
        this.formatDiscount(val, offer);
        return offer;
      },
      formatDiscount(val, target) {
        let result = {};
        if (this.model.JoinNum < 1) {
          target.DiscountPrice = 0;
          target.Remark = "未填写报名人数";
          return;
        }
        if (this.model.CustomerType == 1) {
          //1、判断是否满足双人报名
          result = this.calcDiscount(3, val);
          if (result.money > 0) {
            target.DiscountPrice = result.money;
            target.ActualPrice = target.ActualPrice - result.money;
            target.Remark = result.remark;
          } else {
            result = this.calcDiscount(2, val);
            if (result.money > 0) {
              target.DiscountPrice = result.money;
              target.ActualPrice = target.ActualPrice - result.money;
              target.Remark = result.remark;
            } else {
              result = this.calcDiscount(1, val);
              if (result.money > 0) {
                target.DiscountPrice = result.money;
                target.ActualPrice = target.ActualPrice - result.money;
                target.Remark = result.remark;
              }
            }
          }
        } else if (this.model.CustomerType == 2) {
          result = this.calcDiscount(4, val);
          if (result.money > 0) {
            target.DiscountPrice = result.money;
            target.ActualPrice = target.ActualPrice - result.money;
            target.Remark = result.remark;
          }
        } else {
          target.DiscountPrice = 0;
          target.Remark = "未选择客户类型";
        }
      },
      calcDiscount(type, val) {
        let result = {
          money: 0,
          remark: ""
        };
        val.PreferentialList.forEach(x => {
          if (
            x.PriceDiscountType == type &&
            this.model.JoinNum > 1 &&
            type == 3
          ) {
            result.money =
              parseFloat(val.SellPrice) *
              (parseFloat(x.PriceMoney) / 100.0) *
              this.model.JoinNum;
            result.remark = `双人报名优惠${x.PriceMoney}%`;
          } else if (
            x.PriceDiscountType == type &&
            type == 2 &&
            this.model.JoinNum > 0
          ) {
            result.money =
              parseFloat(val.SellPrice) *
              (parseFloat(x.PriceMoney) / 100.0) *
              this.model.JoinNum;
            result.remark = `单人报名优惠${x.PriceMoney}%`;
          } else if (
            x.PriceDiscountType == type &&
            type == 1 &&
            this.model.JoinNum > 0
          ) {
            let joinNum =
              Math.floor(this.model.JoinNum / (x.BuyNum + x.SendNum)) * x.BuyNum +
              (this.model.JoinNum % (x.BuyNum + x.SendNum));
            result.money =
              val.SellPrice * this.model.JoinNum -
              parseFloat(val.SellPrice) * joinNum;
            result.remark = `买${x.BuyNum}送${x.SendNum}`;
          } else if (
            x.PriceDiscountType == type &&
            type == 4 &&
            this.model.JoinNum > 0
          ) {
            result.money =
              parseFloat(val.SellPrice) *
              (parseFloat(x.PriceMoney) / 100.0) *
              this.model.JoinNum;
            result.remark = `续费优惠${x.PriceMoney}%`;
          }
        });
        return result;
      },
    },
    watch: {

    }
  };

</script>
<style>
</style>
