<template>
  <!-- 汽运单价页面 -->
  <div class="salePlan">
    <div class="top">
      <el-input placeholder="请输入内容" v-model="input" clearable> </el-input>
      <el-button type="primary" class="btn" @click="onclick" :loading="loading">
        <i class="el-icon-search"></i>查询
      </el-button>
      <el-button type="primary" @click="btnclick(0)">
        <i class="el-icon-plus"></i>新增
      </el-button>
       <el-button type="primary" @click="exportAllExcel()"><i class="el-icon-download"></i>导出(Excel)</el-button>
    </div>

<el-tabs v-model="activeName">
      <!-- 正在启用 -->
       <el-tab-pane label="正在启用" name="first">
          <dilTable ref="excelDom" v-bind.sync="option" :loading="loading" :isKuang="isKuang" @func="func">
            <el-table-column
            fixed="right"
            label="操作"
            width="200px"
            align="center"
            >
            <template slot-scope="scope">
              <el-button type="primary" @click="updatePriceclick(scope.row)">修改</el-button>
              <el-button type="primary" @click="deletePrice(scope.row)">删除</el-button>
            </template>
            </el-table-column>
        </dilTable>
      </el-tab-pane>
      <!-- 历史启用 -->
      <el-tab-pane label="历史启用" name="second">
          <dilTable ref="excelDom" v-bind.sync="option2" :loading="loading" :isKuang="isKuang" @func="func">
          </dilTable>
      </el-tab-pane>
    </el-tabs>

    <!-- 承运商模态框 -->
    <el-drawer
      title="运价修改界面"
      :visible.sync="drawer"
      direction="rtl"
      size="40%"
      :show-close="false"
    >
      <div class="operation1">
        <span style="width:10%;align-content: center;">卸货地点</span>
        <el-input
        v-model="newAddressDeliveryAddress"
        style="width:70%"
        ></el-input>
        <el-button type="primary" style="width:15%" @click="updateAddressDeliveryAddress">提交</el-button>
      </div>
      <div class="operation2">
        <span style="width:10%;align-content: center;">运价</span>
        <el-input
        v-model="newPriceValue"
        style="width:30%"
        ></el-input>
        <el-button type="primary" style="width:15%" @click="updatePriceValue">提交</el-button>
      </div>
      <el-input
        placeholder="请输入内容"
        style="margin-top: 10px; margin-left: 20px;width:250px"
        clearable
        v-model="index"
      >
      </el-input
      ><el-button
      type="primary"
      style="margin-left: 4px;"
      @click="queryCarrierName"
    >
      <i class="el-icon-search"></i>查询
    </el-button>
      <el-button type="primary" @click="updateCarrierNamelist">确定修改承运商</el-button>
      <div>
        <!-- 查询所有的承运商 -->
        <el-table
        :data="carrierNameTable"
        style="width:100%"
        max-height="200px"
        :row-key="getRowKeys"
        @selection-change="handleSelectionChange"
        :border="true"
        ref="carrierNameTable"
        >
        <el-table-column
        type="selection"
        :reserve-selection="true"
        >
        </el-table-column>
        <el-table-column
        type="index"
        label="序号"
        >
        </el-table-column>
        <el-table-column
        prop="carrierName"
        label="承运商"
        align="center"
        >
        </el-table-column>
        </el-table>
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        layout="total,prev,pager,next,sizes"
        :total="carrierNametotal"
        :page-sizes="[10, 50, 100, 1000]"
        :page-size="currentPageSize"
        >
        </el-pagination>
      </div>
    </el-drawer>
  </div>
</template>
<script>
export default {
  name: "TransportPrice",
  data() {
    return {
      activeName: "first",
      isKuang:false,
      loading:false,
      input: "",
      drawer:false,
      //承运商
      carrierNameTable:[],
      //卸货地点
      newAddressDeliveryAddress:'',
      //运价
      newPriceValue:'',
      //执行日期
      insertTime:'',
      //修改单价或者卸货地址所需信息
      datalist:{},
      //选中的值
      checkedList:[],
      //承运商总数目
      carrierNametotal:100,
      //当前页数
      currentPage:1,
      //当前页数规格
      currentPageSize:10,
      //搜索框
      index:'',
      //承运商的修改
      carrierIdArray:[],
      option: {
        // 表格请求数据的地址
        requestUrl:
          "/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=0",
      },
      option2: {
        // 表格请求数据的地址
        requestUrl:
          "/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=1",
      },
      tableTitle:'汽运单价'
    };
  },
  methods: {
    exportAllExcel() {
     if (this.activeName == 'first') {
       this.tableTitle = '正在启用的运输单价'
       this.loading = true;
     this.isKuang = true;
     if(this.input){
       this.axios
               .post(
                 "/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=0&con=" +this.input+"&i="+new Date()
               )
               .then(res => {
                 console.log(res.data.data)
                 this.exportAllList = res.data.data.list
                 this.noSettleDetailsColumn=res.data.data.columnData
                 this.exportAllReportToExcel(
                   this.tableTitle,
                   this.exportAllList,
                   this.noSettleDetailsColumn
                 )
               })
     }else{
       this.axios
               .post(
                 "/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=0&i="+new Date()
               )
               .then(res => {
                 console.log(res.data.data)
                 this.exportAllList = res.data.data.list
                 this.noSettleDetailsColumn=res.data.data.columnData
                 this.exportAllReportToExcel(
                   this.tableTitle,
                   this.exportAllList,
                   this.noSettleDetailsColumn
                 )
               })
     }
      }else if (this.activeName == 'second') {
       this.tableTitle = '历史启用的运输单价'
       this.loading = true;
       this.isKuang = true;
     if(this.input){
       this.axios
               .post(
                 "/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=1&con=" +this.input+"&i="+new Date()
               )
               .then(res => {
                 console.log(res.data.data)
                 this.exportAllList = res.data.data.list
                 this.noSettleDetailsColumn=res.data.data.columnData
                 this.exportAllReportToExcel(
                   this.tableTitle,
                   this.exportAllList,
                   this.noSettleDetailsColumn
                 )
               })
     }else{
       this.axios
               .post(
                 "/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=1&con=" +this.input+"&i="+new Date()
               )
               .then(res => {
                 console.log(res.data.data)
                 this.exportAllList = res.data.data.list
                 this.noSettleDetailsColumn=res.data.data.columnData
                 this.exportAllReportToExcel(
                   this.tableTitle,
                   this.exportAllList,
                   this.noSettleDetailsColumn
                 )
               })
     }
       } else {
       }
       this.loading=false
     },
   //导出excel
   exportAllReportToExcel(tableTitle, dataArr, columnData) {
     var title = tableTitle
     let tHeader = []
     let filterVal = []
     columnData.forEach(e1 => {
       if (tHeader.indexOf(e1.label) === -1) {
         tHeader.push(e1.label)
       }
       if (filterVal.indexOf(e1.prop) === -1) {
         filterVal.push(e1.prop)
       }
     })
     //导出为excel
     this.downloadLoading = true
     require.ensure([], () => {
       const {
         export_json_to_excel
       } = require('@/assets/excel/Export2Excel.js') //这里必须使用绝对路径，使用@/+存放export2Excel的路径
       // let list = this.$refs.excelDom.dataTabel;
       let data = dataArr.map(v => filterVal.map(j => v[j])) //3.formatJson格式转换
       export_json_to_excel(tHeader, data, title) // (title)导出的表格名称
     })
   },
    func(){
      this.loading = false;
      this.isKuang = false;
    },
    onclick() {
      this.loading = true;
      this.isKuang = true;
      if(this.input){
        this.option.requestUrl ="/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=0&con=" +this.input+"&i="+new Date();
        this.option2.requestUrl ="/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=1&con=" +this.input+"&i="+new Date();
      }else{
        this.option.requestUrl ="/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=0&i="+new Date();
        this.option2.requestUrl ="/api/v1/ams/getAmsContractTransportPrice1?apiId=109&deleted=1&con=" +this.input+"&i="+new Date();
      }
    },
    btnclick() {
      this.$router.push("/addTransportPrice");
    },
    updatePriceclick(row) {
      this.$router.push({
        name:'addTransportPriceNew',
        params:{
          addressProvince:row.addressProvince,
          addressDistrict:row.addressDistrict,
          addressTown:row.addressTown,
          addressDeliveryAddress:row.addressDeliveryAddress,
          priceValue:row.priceValue,
          haulDistance:row.haulDistance,
          placeId:row.placeId,
          priceDate:row.priceDate
        }
      });
    },
    //修改运价
    //删除运价
    deletePrice(row){
      let mapValue={
        addressProvince:row.addressProvince,
        addressDistrict:row.addressDistrict,
        addressTown:row.addressTown,
        addressDeliveryAddress:row.addressDeliveryAddress
      }
      this.axios.post("/api/v1/ams/deleteSalelPrice",mapValue)
      .then(res=>{
        if(res.data.code==200){
          this.$message.success("删除成功")
        }else{
          this.$message.warning("删除失败")
        }
      })
      this.onclick()
    },
    //修改
    async updatePrice(row){
      this.drawer=true
      this.newAddressDeliveryAddress=row.addressDeliveryAddress
      this.newPriceValue=row.priceValue
      this.datalist.placeId=row.placeId
      this.datalist.addressProvince=row.addressProvince
      this.datalist.addressDistrict=row.addressDistrict
      this.datalist.addressTown=row.addressTown
      this.datalist.addressDeliveryAddress=row.addressDeliveryAddress
      let mapValue={
          pageSize:this.currentPageSize,
          pageNum:this.currentPage,
          index:this.index
        }
      await this.axios.post("/api/v1/ams/getCarrierListByPrice",mapValue).then(res=>{
        console.log("进入了查询承运商界面")
        console.log(res.data)
        this.carrierNameTable=res.data.data
        this.carrierNametotal=res.data.data[1].total
      })
      await this.axios.post("/api/v1/ams/getCarrierListByAddress",this.datalist).
      then(res=>{
        //this.checkedList=res.data.data
      })
      //console.log("初始化时选中的数据")
      //console.log(this.checkedList)
    },
    //修改运价
    updatePriceValue(){
      console.log("查看数据")
      console.log(this.newPriceValue)
      if(this.newPriceValue==null||this.newPriceValue==""){
        this.$message.warning("运价不能为空")
        return
      }
      console.log("进入了修改单价的方法")
      this.datalist.newPriceValue=this.newPriceValue
      console.log(this.datalist)
      this.axios.post("/api/v1/ams/updatePriceValue",this.datalist).
      then(res=>{
        if(res.data.code==200){
          this.$message.success("修改运价成功")
        }else{
          this.$message.warning("修改运价失败")
        }
      })
      this.onclick()
      this.drawer=false
      this.$refs.carrierNameTable.clearSelection()
    },
    //修改卸货地址
    updateAddressDeliveryAddress(){
      if(this.newAddressDeliveryAddress==null||this.newAddressDeliveryAddress==""){
        this.$message.warning("卸货地址不能为空")
        return
      }
      console.log("进入了修改卸货地址的方法")
      this.datalist.newAddressDeliveryAddress=this.newAddressDeliveryAddress
      console.log(this.datalist)
      this.axios.post("/api/v1/ams/updateaddressDeliveryAddress",this.datalist).
      then(res=>{
        console.log(res)
        if(res.data.code==200){
          this.$message.success("修改卸货成功")
        }else{
          this.$message.warning("修改卸货失败")
        }
      })
      this.onclick()
      this.drawer=false
      this.$refs.carrierNameTable.clearSelection()
    },
    getRowKeys(row){
      return row.carrierId
    },
    handleSelectionChange(list){
      console.log("选中的值")
      console.log(list)
      this.checkedList=list
      console.log(this.checkedList)
    },
    async handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.currentPageSize=val
        let mapValue={
          pageSize:this.currentPageSize,
          pageNum:this.currentPage,
          index:this.index
        }
        await this.axios.post("/api/v1/ams/getCarrierListByPrice",mapValue).then(res=>{
        console.log("进入了查询承运商界面")
        console.log(res.data)
        this.carrierNameTable=res.data.data
        this.carrierNametotal=res.data.data[1].total
      })
      },
    async handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.currentPage=val
        let mapValue={
          pageSize:this.currentPageSize,
          pageNum:this.currentPage,
          index:this.index
        }
        await this.axios.post("/api/v1/ams/getCarrierListByPrice",mapValue).then(res=>{
        console.log("进入了查询承运商界面")
        console.log(res.data)
        this.carrierNameTable=res.data.data
        this.carrierNametotal=res.data.data[1].total
      })
    },
    async queryCarrierName(){
      let mapValue={
          pageSize:this.currentPageSize,
          pageNum:this.currentPage,
          index:this.index
        }
        await this.axios.post("/api/v1/ams/getCarrierListByPrice",mapValue).then(res=>{
        console.log("进入了查询承运商界面")
        console.log(res.data)
        this.carrierNameTable=res.data.data
        this.carrierNametotal=res.data.data[1].total
      })
    },
    //修改承运商
    async updateCarrierNamelist(){
      for(let i=0;i<this.checkedList.length;i++){
        this.carrierIdArray.push(this.checkedList[i].carrierId)
      }
      this.datalist.carrierIdArray=this.carrierIdArray
      await this.axios.post("/api/v1/ams/updateCarrierName",this.datalist).then(res=>{
        if(res.data.code==200){
          this.$message.success("修改承运商成功")
        }else{
          this.$message.warning("修改承运商失败")
        }
      })
      console.log("看看数据对不对")
      console.log(this.carrierIdArray)
      console.log(this.$refs)
      this.$refs.carrierNameTable.clearSelection()
      this.carrierIdArray=[]
      this.drawer=false
      this.onclick()
    }
    /*importExcel(file){
      let that = this;
      if (!file) {
        that.$message({
          message: "文件错误!",
          type: "warning"
        });
        return;
      }
      let excelData =[]
      var reader=new FileReader();
      var data=null;
      var workbook = null;
      //设置读取操作
      reader.onload = function (e){
        console.log(e);
        data = e.target.result;
        workbook=XLSX.read(data,{type:'binary'});
        console.log(workbook)
        //只取第一个表的数据
        let rows= XLSX.utils.sheet_to_json(
          workbook.Sheets[workbook.SheetNames[0]]
        );
        console.log(rows)
        let index=1;
        // for (index=1;index<rows.length;index++){
        //   if (
        //     typeof workbook.Sheets[workbook.SheetNames[0]]["A"+index] !=
        //     "undefined"
        //   ){
        //     index++;
        //     break
        //   }
        // }
        // console.log("表头行数:" + index);
        // if(index>=rows.length){
        //   that.$message({
        //     message: "文件错误!",
        //     type: "warning",
        //   });
        //   return
        // }
        if (
          typeof workbook.Sheets[workbook.SheetNames[0]]["A" + index] == 'undefined' ||
          typeof workbook.Sheets[workbook.SheetNames[0]]["B" + index] == 'undefined' ||
          typeof workbook.Sheets[workbook.SheetNames[0]]["C" + index] == 'undefined' ||
          typeof workbook.Sheets[workbook.SheetNames[0]]["D" + index] == 'undefined' ||
          typeof workbook.Sheets[workbook.SheetNames[0]]["E" + index] == 'undefined' ||
          typeof workbook.Sheets[workbook.SheetNames[0]]["F" + index] == 'undefined' ||
          typeof workbook.Sheets[workbook.SheetNames[0]]["G" + index] == 'undefined' ||
          typeof workbook.Sheets[workbook.SheetNames[0]]["H" + index] == 'undefined' ||
          workbook.Sheets[workbook.SheetNames[0]]["A" + index].v != "序号" ||
          workbook.Sheets[workbook.SheetNames[0]]["B" + index].v != "省份" ||
          workbook.Sheets[workbook.SheetNames[0]]["C" + index].v != "市/区" ||
          workbook.Sheets[workbook.SheetNames[0]]["D" + index].v != "县/镇" ||
          workbook.Sheets[workbook.SheetNames[0]]["E" + index].v != "卸货地点" ||
          workbook.Sheets[workbook.SheetNames[0]]["F" + index].v != "参考运距（公里）" ||
          workbook.Sheets[workbook.SheetNames[0]]["G" + index].v != "运价（元/吨）" ||
          workbook.Sheets[workbook.SheetNames[0]]["H" + index].v != "吨公里（元/吨.km）"
        ){
          if (
            typeof workbook.Sheets[workbook.SheetNames[0]]["A" + index] == 'undefined' ||
            workbook.Sheets[workbook.SheetNames[0]]["A" + index].v != "序号"
          ) {
            that.$message({
              message: "表格格式错误:序号错误",
              type: "warning"
            });
          }
          if (
            typeof workbook.Sheets[workbook.SheetNames[0]]["B" + index] == 'undefined' ||
            workbook.Sheets[workbook.SheetNames[0]]["B" + index].v != "省份"
          ) {
            that.$message({
              message: "表格格式错误:省份错误",
              type: "warning"
            });
          }
          if (
            typeof workbook.Sheets[workbook.SheetNames[0]]["C" + index] == 'undefined' ||
            workbook.Sheets[workbook.SheetNames[0]]["C" + index].v != "市/区"
          ) {
            that.$message({
              message: "表格格式错误:市/区错误",
              type: "warning"
            });
          }
          if (
            typeof workbook.Sheets[workbook.SheetNames[0]]["D" + index] == 'undefined' ||
            workbook.Sheets[workbook.SheetNames[0]]["D" + index].v != "县/镇"
          ) {
            that.$message({
              message: "表格格式错误:县/镇错误",
              type: "warning"
            });
          }
          if (
            typeof workbook.Sheets[workbook.SheetNames[0]]["E" + index] == 'undefined' ||
            workbook.Sheets[workbook.SheetNames[0]]["E" + index].v != "卸货地点"
          ) {
            that.$message({
              message: "表格格式错误:卸货地点错误",
              type: "warning"
            });
          }
          if (
            typeof workbook.Sheets[workbook.SheetNames[0]]["F" + index] == 'undefined' ||
            workbook.Sheets[workbook.SheetNames[0]]["F" + index].v != "参考运距（公里）"
          ) {
            that.$message({
              message: "表格格式错误:参考运距（公里）错误",
              type: "warning"
            });
          }
          if (
            typeof workbook.Sheets[workbook.SheetNames[0]]["G" + index] == 'undefined' ||
            workbook.Sheets[workbook.SheetNames[0]]["G" + index].v != "运价（元/吨）"
          ) {
            that.$message({
              message: "表格格式错误:运价（元/吨）错误",
              type: "warning"
            });
          }
          if (
            typeof workbook.Sheets[workbook.SheetNames[0]]["G" + index] == 'undefined' ||
            workbook.Sheets[workbook.SheetNames[0]]["H" + index].v != "吨公里（元/吨.km）"
          ) {
            that.$message({
              message: "表格格式错误:吨公里（元/吨.km）错误",
              type: "warning"
            });
          }
        }
        //读取表格
        for (let i = index+1; i <= rows.length+1 ; i++){
          console.log(workbook.Sheets[workbook.SheetNames[0]]["B" + i].v)
        }
      }
      reader.readAsBinaryString(file.raw);
    }*/
  },

};
</script>
<style lang='scss' scoped>
.salePlan {
  .top{
    padding: 1.25rem 0.375rem;
    .el-input {
      width: 20%;
      margin-right: 1.25rem;
    }
  }
  .operation1{
    display: flex;
    flex-direction: row;
    margin-bottom: 20px;
  }
  .operation2{
    display: flex;
    flex-direction: row;
    margin-bottom: 20px;
  }
}
</style>
