<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="客户名称" prop="quotCustomer">
        <el-input
          v-model="queryParams.quotCustomer"
          placeholder="请输入客户名称"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table width="100%"  v-loading="loading" :data="quotsList" :row-class-name="rowQuotsIndex">
      <el-table-column fixed="left" label="序号" align="center" prop="index" width="50"/>
      <el-table-column fixed="left" label="操作" align="center" width="60" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" @click="handleDeleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="quot_id" align="center" prop="quot_id" v-if="false"/>
      <el-table-column label="报价单号" width="260" align="center" prop="quotCode">
        <template slot-scope="scope">
          <el-link :underline="false" type="primary" @click="handleDetail(scope.row)">{{scope.row.quotCode}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="报价客户" width="250" align="center" prop="quotCustomer" />
      <el-table-column label="报价项目" width="250" align="center" prop="quotProject" />
      <el-table-column label="总价" width="100" align="center" prop="totalPrice" />
      <el-table-column label="联系人" align="center" prop="quotLxr" />
      <el-table-column label="联系人电话" width="100" align="center" prop="quotLxrdh" />
      <el-table-column label="创建日期" width="180" align="center" prop="createTime" />
      <el-table-column label="更新日期" width="180" align="center" prop="updateTime" />
    </el-table>

    <!-- 报价详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1050px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="询价单位" prop="quotCustomer">
              <el-input v-model="form.quotCustomer"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="quotProject">
              <el-input v-model="form.quotProject"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="8">
            <el-form-item label="联系人" prop="quotLxr">
              <el-input v-model="form.quotLxr"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="quotLxrdh">
              <el-input v-model="form.quotLxrdh"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价">
              <el-input class="totalPrice-input" v-model="sumSelectedResultData"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="24">
            <el-form-item label="总金额" prop="totalPrice" v-if="false">
              <el-input v-model="form.totalPrice"/>
            </el-form-item>
            <el-form-item label="设置折扣率" label-width="100px">
              <el-input style="width:65px" v-model="perc" size="small" @blur="changeData" @keyup.enter.native="changeData"></el-input>
              <el-input style="width:65px;margin-left: 5px" v-model="perc2" size="small" @blur="changeData" @keyup.enter.native="changeData"></el-input>
              <!--总价:<span style="color:red;font-size: 15px">{{sumSelectedResultData}} 元</span>-->
              <el-select v-model="form.rbDateUid" style="margin-left: 20px;width: 235px;" :disabled="selectedResultData.length==0">
                <el-option
                  v-for="item in versionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  @click.native="selectRbDate(item.value)"/>
              </el-select>
              <el-button style="float: right;margin-left: 5px;" size="small" type="success" icon="el-icon-document" @click="handleMadeQuotClick" :disabled="selectedResultData.length==0">生成报价单</el-button>
              <el-button style="float: right;" size="small" type="warning" icon="el-icon-folder" @click="handleSaveClick" :disabled="selectedResultData.length==0">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-table v-loading="selectedResultLoading" width="100%;" :row-class-name="selectedResultIndex" :data="selectedResultData" height="350px">
          <el-table-column fixed="left" label="" align="center" prop="index" width="50"/>
          <el-table-column label="版本uid" align="center" prop="uid_0" v-if="false"/>
          <el-table-column fixed="left" label="产品型号" align="center" prop="name_0" width="180" />
          <el-table-column label="型号" align="center" prop="name_1" v-if="false"/>
          <el-table-column label="规格" align="center" prop="spec" v-if="false"/>
          <el-table-column label="电压" align="center" prop="voltage"/>
          <el-table-column label="红本价(元)" align="center" prop="price"/>
          <el-table-column label="单位" align="center" prop="stu"/>
          <el-table-column label="一次折扣" align="center" prop="per">
            <template slot-scope="scope">
              <el-input v-model="scope.row.per" @blur="changeRowData" @keyup.enter.native="changeRowData"/>
            </template>
          </el-table-column>
          <el-table-column label="二次折扣" align="center" prop="per2">
            <template slot-scope="scope">
              <el-input v-model="scope.row.per2" @blur="changeRowData" @keyup.enter.native="changeRowData"/>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="setPrice"/>
          <el-table-column label="数量调整" align="center" prop="count">
            <template slot-scope="scope">
              <el-input v-model="scope.row.count" @blur="changeRowData" @keyup.enter.native="changeRowData"/>
            </template>
            </el-table-column>
          <el-table-column label="总价" align="center" prop="allPrice"/>
        </el-table>
      </el-form>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<style>
  .totalPrice-input .el-input__inner {
    color: red;
  }
</style>
<script>
  import {toDecimal, versionList,listQuots,getQuotDetail,deleteQuots,updateSelectedResultData,madeQuot,saveQuot } from "@/api/redBook/redBook";

  export default {
      name: "quots",
      data() {
        return {
          // 遮罩层
          loading: true,
          // 显示搜索条件
          showSearch: true,
          // 总条数
          total: 0,
          //报价单数据
          quotsList: [],
          // 时间范围
          dateRange: [],
          //调价日期
          versionList: [], // 调价版本数据列表
          // 查询参数
          queryParams: {
            pageNum: 1,
            pageSize: 10
          },

          //表单
          form: {},
          // 弹出层标题
          title: "",
          // 是否显示弹出层
          open: false,
          // 列表数据
          selectedResultData: [],

          //折扣率 初始值
          perc: 0.8,
          perc2: '',
          selectedResultLoading: false,
        }
      },
      created() {
        this.getList();
        this.getVersionList();
      },
      methods: {
        /** 查询报价单列表 */
        getList() {
          this.loading = true;
          listQuots(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.quotsList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        },
        //获取调价日期
        getVersionList(){
          versionList(this.queryParams).then(response => {
            this.versionList = response.versionList;
          });
        },

        rowQuotsIndex({ row, rowIndex }) {
          row.index = rowIndex + 1;
        },
        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNum = 1;
          this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
          this.resetForm("queryForm");
          this.handleQuery();
        },

        /** 查看详情按钮操作 */
        handleDetail(row) {
          const quotId = row.quot_id;
          getQuotDetail(quotId).then(response => {
            this.form = response.data;
            this.selectedResultData = response.data.selectedResultData;
            this.open = true;
            this.title = "报价单信息";
          })
        },
        /** 数据序号 */
        selectedResultIndex({ row, rowIndex }) {
          row.index = rowIndex + 1;
        },

        /** 删除报价单 */
        handleDeleteClick(row) {
          const quotId = row.quot_id;
          deleteQuots(quotId).then(response => {
            this.$message.success("删除成功");
            this.getList();
          })
        },

        //一次折扣率变化时触发
        changeData() {
          // 校验折扣率格式
          const pattern = /^\d+(\.\d+)?$/;
          if(this.perc) {
            if (!pattern.test(this.perc)) {
              this.$message.warning("折扣率格式错误!");
              return;
            }
          }
          if(this.perc2) {
            if (!pattern.test(this.perc2)) {
              this.$message.warning("折扣率格式错误!");
              return;
            }
          }

          // 遍历表格数据进行计算
          this.selectedResultData.forEach((row, index) => {
            // 进行其他计算
            this.$set(this.selectedResultData, index, {
              ...row,
              per: this.perc,
              per2: this.perc2,
              setPrice: toDecimal(row.price * (this.perc?this.perc:1) * (this.perc2?this.perc2:1)),
              allPrice: toDecimal(row.count * row.price * (this.perc?this.perc:1) * (this.perc2?this.perc2:1)),
            });
          })
        },
        // 行内数据监听
        changeRowData() {
          // 遍历表格数据进行计算
          this.selectedResultData.forEach((row, index) => {
            // 进行其他计算
            this.$set(this.selectedResultData, index, {
              ...row,
              setPrice: toDecimal(row.price * (row.per?row.per:1) * (row.per2?row.per2:1)),
              allPrice: toDecimal(row.count * row.price * (row.per?row.per:1) * (row.per2?row.per2:1)),
            });
          })
        },
        //选择调价日期
        selectRbDate(uid){
          this.selectedResultData.forEach((row, index) => {
            this.$set(this.selectedResultData, index, {
              ...row,
              uid_0: uid // 重新设置为所选版本uid
            });
          });
          this.selectedResultLoading = true;
          //更新已选结果数据-单价、金额
          updateSelectedResultData(this.selectedResultData).then(response => {
            for (let i = 0; i < this.selectedResultData.length; i++) {
              for (let j = 0; j < response.data.length; j++) {
                // 检查型号、规格、电压等级是否相等
                if (
                  this.selectedResultData[i].name_0 === response.data[j].name_0 &&
                  this.selectedResultData[i].spec === response.data[j].spec &&
                  this.selectedResultData[i].voltage === response.data[j].voltage
                ) {
                  this.selectedResultData[i].price = response.data[j].setPrice;
                  const setPrice = toDecimal(this.selectedResultData[i].price * (this.selectedResultData[i].per?this.selectedResultData[i].per:1) * (this.selectedResultData[i].per2?this.selectedResultData[i].per2:1));
                  const allPrice = toDecimal(this.selectedResultData[i].count * this.selectedResultData[i].price * (this.selectedResultData[i].per?this.selectedResultData[i].per:1) * (this.selectedResultData[i].per2?this.selectedResultData[i].per2:1));

                  this.selectedResultData[i].setPrice = setPrice;
                  this.selectedResultData[i].allPrice = allPrice;
                }
              }
            }
            this.selectedResultLoading = false;
          });
        },

        // 报价单保存修改
        handleSaveClick() {
          const allPrice = this.selectedResultData.reduce((sum, row) => sum + parseFloat(row.allPrice), 0);
          this.form.totalPrice = allPrice.toFixed(2);
          this.form.selectedResultData = this.selectedResultData;
          saveQuot(this.form).then(response => {
            this.$modal.msgSuccess("修改报价单成功");
            this.open = false;
            this.getList();
          })
        },

        // 报价单生成
        handleMadeQuotClick() {
          this.form.selectedResultData = this.selectedResultData;
          madeQuot(this.form).then(response => {
            this.$modal.msgSuccess("生成报价单成功");
            // 处理返回的文件流
            const content = response;
            const blob = new Blob([content]);
            const fileName = "BJD_"+this.getTodayCourse()+".xls";
            if ("download" in document.createElement("a")) {
              // 非IE下载
              const elink = document.createElement("a");
              elink.download = fileName;
              elink.style.display = "none";
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href); // 释放URL 对象
              document.body.removeChild(elink);
            }
            else {
              // IE10+下载
              navigator.msSaveBlob(blob, fileName);
            }
          });
        },
        // 获取当前时间
        getTodayCourse(){
          const myDate = new Date();
          //获取当前年
          const year = myDate.getFullYear();
          //获取当前月
          const month = myDate.getMonth() + 1;
          //获取当前日
          const date = myDate.getDate();
          const h = myDate.getHours();       //获取当前小时数(0-23)
          const m = myDate.getMinutes();     //获取当前分钟数(0-59)
          const s = myDate.getSeconds();
          return year + '-' + this.p(month) + "-" + this.p(date) + " " + this.p(h) + ':' + this.p(m) + ":" + this.p(s)
        },
        p(s) {
          return s < 10 ? '0' + s : s;
        }
      },
      computed: {
        // 数据汇总
        sumSelectedResultData() {
          const allPrice = this.selectedResultData.reduce((sum, row) => sum + parseFloat(row.allPrice), 0);
          return allPrice.toFixed(2);
        },
      },
    }
</script>

<style scoped>

</style>
