<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="getList(activeName)">
      <el-tab-pane label="预估仓储费用设置" name="1">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="90px"
        >
          <el-form-item label="月份:" prop="configMonth">
            <el-date-picker
              v-model="queryParams.configMonth"
              type="month"
              value-format="yyyyMM"
              placeholder="请选择月份">
            </el-date-picker>
          </el-form-item>
          <el-row :gutter="10" class="mb8" type="flex" justify="end">
            <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-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              >新增</el-button
            >
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList(1)"></right-toolbar>
        </el-row>

        <el-table
          ref="proTable"
          :height="tableHeight"
          border
          v-loading="loading"
          :data="postList"
        >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column label="月份" min-width="90" align="center" prop="configMonth" />
          <el-table-column label="打包费用(元)/每包裹" min-width="150" align="center" prop="packageFee" />
          <el-table-column label="包裹商品数大于3件每件加收打包费(元)/每件" min-width="160" align="center" prop="packageTreeFee" />
          <el-table-column label="仓储租赁分摊(元)/每包裹" min-width="150" align="center" prop="warehouseFee" />
          <el-table-column label="包材(元)/每包裹" min-width="150" align="center" prop="createBy">
            <template slot-scope="scope">
              <div v-for="(item, index) in scope.row.packageMaterialFeeList" :key="index">
                {{ item.packageFeeName }}-{{ item.packageFee }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="创建人" min-width="140" align="center" prop="createdBy" />
          <el-table-column label="创建时间" min-width="140" align="center" prop="createdTime" />
          <el-table-column
            label="操作"
            width="120"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="showChart(scope.row,1)"
                >编辑</el-button
              >
              <el-button size="mini" type="text" @click="showChart(scope.row,2)"
                >日志</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="仓储费用账单导入" name="2">
        
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleImport"
              >导入账单</el-button
            >
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList(2)"></right-toolbar>
        </el-row>

        <el-table
          ref="proTable"
          :height="tableHeight"
          border
          v-loading="loading"
          :data="postList2"
        >
          <el-table-column label="账单文件名称" min-width="150" align="center" prop="fileName" />
          <el-table-column label="账单发货日期范围" min-width="300" align="center" prop="startTime">
            <template slot-scope="scope">
              {{ scope.row.startTime }} ~ {{ scope.row.endTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作人" min-width="150" align="center" prop="createdBy" />
          <el-table-column label="导入时间" min-width="150" align="center" prop="createdTime" />
          <el-table-column
            label="操作"
            width="120"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="dowaLoadBill(scope.row)"
                >下载</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        
      </el-tab-pane>
    </el-tabs>  

    <pagination
      v-show="total > 0&&activeName==1"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList(1)"
      class="fixed-pagination"
    />

    <pagination
      v-show="total2 > 0&&activeName==2"
      :total="total2"
      :page.sync="queryParams2.pageNum"
      :limit.sync="queryParams2.pageSize"
      @pagination="getList(2)"
      class="fixed-pagination"
    />


 
    <!-- 关联商品 -->
    <el-dialog
      :title="title"
      top="50px"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="spuRef" :model="form" label-width="120px">
        <el-form-item
          label="月份:"
          :rules="[{ required: true, message: '请选择月份', trigger: 'change' }]"
        >
          <el-date-picker
            :disabled="true"
            v-model="form.configMonth"
            type="month"
            value-format="yyyyMM"
            placeholder="请选择月份">
          </el-date-picker>
          
        </el-form-item>

        <el-table ref="addTable" border v-loading="loading" :data="attrLists">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column min-width="210" label="费用项目" align="center" prop="attrName1" />
            <el-table-column
              label="类目"
              min-width="80"
              align="center"
              prop="attrName2"
            />
            <el-table-column
              label="价目(元/每包裹[每件])"
              min-width="210"
              align="center"
              prop="attrName3"
            >
            <template slot-scope="scope">
              <div class="input-box">
                <el-input-number
                  v-model="scope.row.attrValue"
                  type="number"
                  :min="0"
                  placeholder="2位小数"
                  clearable
                  style="width: 140px"
                />{{ scope.row.attrName3 }}
              </div>
              
            </template>
            </el-table-column>
            <el-table-column
              label="备注"
              min-width="350"
              align="center"
              prop="attrName4"
            />
          </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="open = fasle">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="仓储费用设置日志"
      top="50px"
      :visible.sync="open2"
      width="800px"
      append-to-body
    >
      <el-table ref="addTable2" border v-loading="loading" :data="logTableList">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column min-width="180" label="费用项" align="center" prop="logType" />
        <el-table-column
          label="价目"
          min-width="180"
          align="center"
          prop="logMsg"
        />
        <el-table-column
          label="修改人"
          min-width="180"
          align="center"
          prop="createBy"
        />
        <el-table-column
          label="修改时间"
          min-width="180"
          align="center"
          prop="createTime"
        />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="open2 = fasle">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="500px"
      append-to-body
      
    >
    <el-form ref="spuRef" :model="form2" label-width="140px">
        <el-form-item
          label="账单发货日期范围:"
          :rules="[{ required: true, message: '请选择账单发货日期范围', trigger: 'change' }]"
        >
          <el-date-picker
            v-model="form2.dateRange"
            :picker-options="pickerOptions"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width: 325px"
            @change="dateChange"
          ></el-date-picker>
          
        </el-form-item>
    </el-form>

      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :disabled="upload.isUploading"
        class="warehouse-dialog"
        :data='{
          "endDate": form2.dateRange?form2.dateRange[1]:"",
          "startDate": form2.dateRange?form2.dateRange[0]:""
        }'  
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text" :class="upload.isUploading?'disabled-text':''">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <p style="color: #ed5565;">注意事项：发货单sheet：接单时间	订单编号	出库单号	原始单号	订单类别	仓库	店铺	出库单状态	发货状态	回传状态	货品编号	品牌	运输费用	操作费用	纸箱费用</p>
          <!-- <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          > -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { 
  warehouseConfigList,
  warehouseConfigAdd,
  warehouseMaxMonth,
  warehouseConfigUpdate,
  warehouseConfigDetail,
  warehouseConfigLogs,
  billUploadList,
  billValid
} from '@/api/saleConfig/warehouseCost';
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
import { getToken } from "@/utils/auth";

export default {
  name: "SpuList",
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      total2: 0,
      // 岗位表格数据
      postList: [],
      postList2: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      activeName: '1',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        configMonth: "",
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: { 
        "configMonth": "",
        "packageFee": '',
        "packageMaterialFeeList": [],
        "packageTreeFee": '',
        "warehouseFee": ''
      },
      timer: null,
      attrOpen: false,
      title2: "",
      chartLading: true,
      loadDataStatus: true,
      tableHeight: "auto",
      logTableList: [],
      attrLists: [{
        attrName1: '打包费用',
        attrName2: '',
        attrName3: '每个包裹',
        attrName4: '打包费用按月度总订单数阶梯收费，月初预估当前月总订单量后，设置预估的每个包裹打包费用',
        attrValue: 0
      },{
        attrName1: '包裹商品数大于3件每件加收打包费',
        attrName2: '',
        attrName3: '每件',
        attrName4: '每个包裹多于3件商品，多出的每件商品需加收费用',
        attrValue: 0
      },{
        attrName1: '仓储租赁分摊',
        attrName2: '',
        attrName3: '每个包裹',
        attrName4: '仓储租赁费用按每平方米单价算出总费用后，按月初预估总订单数，设置预估的每个包裹仓储租赁分摊费用',
        attrValue: 0
      },{
        attrName1: '包材',
        attrName2: '手机',
        attrName3: '每件',
        attrName4: '每台手机收取包材费用，包括纸箱、填充物、封箱胶',
        attrValue: 0
      },{
        attrName1: '包材',
        attrName2: '平板',
        attrName3: '每件',
        attrName4: '每台平板收取包材费用，包括纸箱、填充物、封箱胶',
        attrValue: 0
      },{
        attrName1: '包材',
        attrName2: '电脑',
        attrName3: '每件',
        attrName4: '每台电脑收取包材费用，包括纸箱、填充物、封箱胶',
        attrValue: 0
      }],
      form2:{
        dateRange:[]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: true,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/warehouse/fee/config/bill/upload",
      },
    };
  },
  created() {
    this.getList(1);
  },
  mounted() {},
  methods: {
    handleCheckedCitiesChange(value) {
      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.cities.length;
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      this.cities = value;
    },
    handleImport(){
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 查询岗位列表 */
    getList(type) {
      this.loading = true;
      if(type==1){
        warehouseConfigList(this.queryParams).then((response) => {
          this.postList = response.data.warehouseFeeConfigConfigListResDTOS;
          this.total = response.data.total;
          this.loading = false;

          this.$nextTick(() => {
            const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 260;
            this.tableHeight = height + "px";
          });
        });
      }else{
        billUploadList(this.queryParams2).then((response) => {
          this.postList2 = response.data.warehouseFeeBillListResDTOS;
          this.total2 = response.data.total;
          this.loading = false;

          this.$nextTick(() => {
            const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 260;
            this.tableHeight = height + "px";
          });
        });
      }
    
    },
    dowaLoadBill(row){
      window.open('https://newfirst.oss-cn-shanghai.aliyuncs.com/'+row.filePath);
    },
    // 表单重置
    reset() {
      this.form = { 
        "configMonth": "",
        "packageFee": '',
        "packageMaterialFeeList": [],
        "packageTreeFee": '',
        "warehouseFee": ''
      };
      // this.attrLists = [];
      this.attrLists.forEach(i=>{
        i.attrValue = '';
      })
      this.resetForm("form");
    },
    dateChange(value){
      console.log(value);
      if(value==null || value.length==0){ 
        this.upload.isUploading = true;
      }
      billValid({
        "endDate": value[1],
        "startDate": value[0]
      }).then(res=>{
        if(res.data==1){
          this.upload.isUploading = false;
        }
        if(res.data==2){
          this.$confirm('存在相同时间范围,是否覆盖？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.upload.isUploading = false;
          }).catch(() => {
            this.upload.isUploading = true;
            this.form2.dateRange = [];
          });
        }
        if(res.data==3){
          this.upload.isUploading = true;
          this.form2.dateRange = [];
          this.$message.warning('存在时间冲突不允许导入');
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList(1);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      warehouseMaxMonth().then(res=>{
        this.form.configMonth = res.data;
        this.form.packageMaterialFeeList = [{
          "packageFee": 0,
          "packageFeeName": "手机"
        },{
          "packageFee": 0,
          "packageFeeName": "平板"
        },{
          "packageFee": 0,
          "packageFeeName": "电脑"
        }]
        this.open = true;
        this.title = "新增配置";
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 修改按钮操作 */
    showChart(row,type) {
      if(type==1){
        warehouseConfigDetail(row.id).then(res=>{
          if(res.status==200){
            this.open = true;
            this.title = "编辑配置";
            this.form.configMonth = res.data.configMonth;
            this.form.id = res.data.id;
            this.form.packageMaterialFeeList = res.data.packageMaterialFeeList;
            this.attrLists[0].attrValue = res.data.packageFee;
            this.attrLists[1].attrValue = res.data.packageTreeFee;
            this.attrLists[2].attrValue = res.data.warehouseFee;
            this.attrLists[3].attrValue = res.data.packageMaterialFeeList[0].packageFee;
            this.attrLists[4].attrValue = res.data.packageMaterialFeeList[1].packageFee;
            this.attrLists[5].attrValue = res.data.packageMaterialFeeList[2].packageFee;
            
          }
        })
      }else{
        warehouseConfigLogs(row.id).then(res=>{
          if(res.status==200){
            this.open2 = true;
            this.logTableList = res.data
          }
        })
      }
     
    },
    submitDataScope() {
      let status = true;
      this.attrLists.forEach((items) => {
        if(items.attrValue===0){
          status = false;
        }
      });
      if(!status){
        this.$message.warning('请输入完整配置');
        return false;
      }

      this.form.packageFee = this.attrLists[0].attrValue;
      this.form.packageTreeFee = this.attrLists[1].attrValue;
      this.form.warehouseFee = this.attrLists[2].attrValue;
      this.form.packageMaterialFeeList[0].packageFee = this.attrLists[3].attrValue;
      this.form.packageMaterialFeeList[1].packageFee = this.attrLists[4].attrValue;
      this.form.packageMaterialFeeList[2].packageFee = this.attrLists[5].attrValue;


      if (this.title == "新增配置") {
        warehouseConfigAdd(this.form).then((res) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList(1);
        });
      } else {
        warehouseConfigUpdate(this.form).then((res) => {
          this.$modal.msgSuccess("编辑成功");
          this.open = false;
          this.getList(1);
        });
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList(2);
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload(
        "/warehouse/fee/config/export",
        data,
        `仓储费用_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.newDownload(
      //   "spu/importTemplate",
      //   {},
      //   `spu_template_${new Date().getTime()}.xlsx`
      // );
      window.location.href = 'https://newfirst.oss-cn-shanghai.aliyuncs.com/pddActivity/%E6%8B%BC%E5%A4%9A%E5%A4%9A%E6%B4%BB%E5%8A%A8.xlsx';
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}
.input-box{
  text-align: left;
}
.disabled-text{
  em{
    color: #999;
  }
  
}
</style>
<style lang="scss">
  .warehouse-dialog {
    .el-upload{
      width: 100%;
    }
    .el-upload-dragger{
      width: 100%;
    }
  }
</style>
