<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="申请编号" prop="fBillno">
        <el-input
          v-model="queryParams.fBillno"
          placeholder="请输入系统编号"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="fCorpid">
        <el-input
          v-model="queryParams.fCorpid"
          placeholder="请输入货权方"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="creatBy">
        <el-select
          v-model="queryParams.creatBy"
          filterable
          remote
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
          :remote-method="corpsRemoteMethod"
          placeholder="请输入结算单位"
        >
          <el-option
            v-for="(dict, index) in fMblnoOptions"
            :key="index.fId"
            :label="dict.fName"
            :value="dict.fId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="daterange"
          size="small"
          style="width: 200px"
          v-model="queryParams.remark"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="申请金额" prop="money">
        <el-input
          type="daterange"
          size="small"
          style="width: 100px"
          v-model="moneys"
        >
        </el-input>
        <el-input
          type="daterange"
          size="small"
          style="width: 100px"
          v-model="moneye"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="申请日期" prop="applyTime">
        <el-date-picker
          type="daterange"
          size="small"
          style="width: 240px"
          @change="timeMethods"
          v-model="queryParams.applyTime"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['finance:charge:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['finance:charge:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['finance:charge:remove']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['finance:charge:export']"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          :disabled="single"
          @click="handleUpdate(null, 2)"
          v-hasPermi="['agreement:agreementStorage:export']"
        >复制新增
        </el-button>
      </el-col>
      <div class="tabSetting">
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
        <div style="margin: 0 12px">
          <el-button
            icon="el-icon-setting"
            size="mini"
            circle
            @click="showSetting = !showSetting"
          ></el-button>
        </div>
      </div>
    </el-row>
    <el-dialog
      title="自定义列显示"
      :visible.sync="showSetting"
      width="700px"
      v-dialogDrag
    >
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span
              style="
                display: inline-block;
                width: 3px;
                height: 20px;
                margin-right: 5px;
                float: left;
                margin-top: 2px;
              "
            ></span>
          </span>
        </div>
      </template>
      <div>配置排序列数据（拖动调整顺序）</div>
      <div style="margin-left: 17px">
        <el-checkbox
          v-model="allCheck"
          label="全选"
          @change="allChecked"
        ></el-checkbox>
      </div>
      <div style="padding: 4px; display: flex; justify-content: center">
        <draggable
          v-model="setRowList"
          group="site"
          animation="300"
          @start="onStart"
          @end="onEnd"
          handle=".indraggable"
        >
          <transition-group>
            <div
              v-for="item in setRowList"
              :key="item.surface"
              class="listStyle"
            >
              <div style="width: 500px" class="indraggable">
                <div class="progress" :style="{ width: item.width + 'px' }">
                  <el-checkbox
                    :label="item.name"
                    v-model="item.checked"
                    :true-label="0"
                    :false-label="1"
                    >{{ item.name }}
                  </el-checkbox>
                </div>
              </div>
              <el-input-number
                v-model.number="item.width"
                controls-position="right"
                :min="1"
                :max="500"
                size="mini"
              ></el-input-number>
            </div>
          </transition-group>
        </draggable>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetting = false">取 消</el-button>
        <el-button @click="delRow" type="danger">重 置</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </span>
    </el-dialog>

    <el-table
      v-loading="loading"
      :data="chargeList"
      @selection-change="handleSelectionChange"
      show-summary
      :summary-method="listTotal"
    >
      <el-table-column type="selection" width="100" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="55"
        align="center"
        fixed
      />
      <el-table-column
        v-for="(item, index) in getRowList"
        :key="index"
        :label="item.name"
        :width="item.width"
        :prop="item.label"
        align="center"
        :show-overflow-tooltip="true"
        sortable
        :fixed="item.fixed"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="check(scope.row, 0)"
            v-hasPermi="['finance:contrast:edit']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row,1)"
            v-hasPermi="['finance:charge:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['finance:charge:remove']"
            >删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { listCharge, delCharge, delCharges, exportCharge, listCorps, delCharge_s, delCharge_ss,exportWarehousebillsitems,
} from "@/api/kaihe/applyForInvoice/invoiceInformation";
import { listFees } from "@/api/basicdata/fees";
import print from "print-js";
import AddOrUpdate from "@/views/viewApproval";
import ApprovalComments from "@/views/startApproval";
import { queryUserVal } from "@/api/warehouseBusiness/agreement";
import Global from "@/layout/components/global";
import draggable from "vuedraggable";
import Vue from "vue";
import Cookies from "js-cookie";
import { addSet, select } from "@/api/system/set";
Vue.directive("dialogDrag", {
  bind(el, binding, vnode, oldVnode) {
    const dialogHeaderEl = el.querySelector(".el-dialog__header");
    const dragDom = el.querySelector(".el-dialog");
    const enlarge = el.querySelector(".enlarge");
    dialogHeaderEl.style.cursor = "move";

    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);
    if (enlarge) {
      enlarge.onclick = (e) => {
        dragDom.style.top = "0px";
        dragDom.style.left = "0px";
      };
    }
    dialogHeaderEl.onmousedown = (e) => {
      // 鼠标按下，计算当前元素距离可视区的距离
      const disX = e.clientX - dialogHeaderEl.offsetLeft;
      const disY = e.clientY - dialogHeaderEl.offsetTop;

      // 获取到的值带px 正则匹配替换
      let styL, styT;

      // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
      if (sty.left.includes("%")) {
        styL =
          +document.body.clientWidth * (+sty.left.replace(/\%/g, "") / 100);
        styT =
          +document.body.clientHeight * (+sty.top.replace(/\%/g, "") / 100);
      } else {
        styL = +sty.left.replace(/\px/g, "");
        styT = +sty.top.replace(/\px/g, "");
      }

      document.onmousemove = function (e) {
        // 通过事件委托，计算移动的距离
        const l = e.clientX - disX;
        const t = e.clientY - disY;

        // 移动当前元素

        if (t + styT >= 0) {
          dragDom.style.top = `${t + styT}px`;
        }
        dragDom.style.left = `${l + styL}px`;
        // 将此时的位置传出去
        // binding.value({x:e.pageX,y:e.pageY})
      };

      document.onmouseup = function (e) {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
  },
});

export default {
  name: "Charge",
  data() {
    return {
      drag: false,
      tableDate: [
        {
          surface: "1",
          label: "fBillno",
          name: "申请编号",
          fixed:"left",
          checked: 0,
          width: 120,
        },
        {
          surface: "2",
          label: "fCorpidName",
          name: "客户名称",
          fixed:"left",
          checked: 0,
          width: 120,
        },
        {
          surface: "3",
          label: "fCtrlcorpid ",
          name: "开票单位",
          fixed:"left",
          checked: 0,
          width: 120,
        },
        {
          surface: "4",
          label: "fAmtdr",
          name: "金额",
          fixed:"left",
          checked: 0,
          width: 120,
        },
        {
          surface: "5",
          label: "createTime",
          name: "申请日期",
          fixed:"left",
          checked: 0,
          width: 120,
        },
        {
          surface: "6",
          label: "createBy",
          name: "申请人",
          fixed:"left",
          checked: 0,
          width: 120,
        },
        {
          surface: "7",
          label: "createName",
          name: "申请单位",
          checked: 0,
          width: 120,
        },
        {
          surface: "8",
          label: "fBillstatus",
          name: "状态",
          checked: 0,
          width: 120,
        },
        {
          surface: "9",
          label: "updateTime",
          name: "审核日期",
          checked: 0,
          width: 120,
        },
        {
          surface: "10",
          label: "updateBy",
          name: "审核人",
          checked: 0,
          width: 120,
        },
        {
          surface: "11",
          label: "remark",
          name: "备注",
          checked: 0,
          width: 120,
        }
      ],
      setRowList: [],
      getRowList: [],
      //自定义列宽
      allCheck: false,
      showSetting:false,
      Lander: "",
      Operator: "",
      tablefilter: false,
      //打印表
      fWbuOptions: [],
      // 遮罩层
      loading: true,
      selection: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totAL: 0,
      Ttime: 0,
      moneys:'',
      moneye:'',
      // 财务数据主表格数据
      chargeList: [],
      // 弹出层标题
      title: "",
      fMblnoOptions: "",
      // 主表查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fBillno: null,
        fCorpid: null,
        creatBy: null,
        remark: null,
        money: [],
        createTime: null,
      },
    };
  },
  components: {
    draggable,
    AddOrUpdate,
    ApprovalComments,
  },
  created() {
    this.setRowList = this.tableDate;
    this.getRowList = this.tableDate;
    this.getList();
    this.getRow();
  },
  activated() {

  },
  methods: {

    //导出明细
    handleExportItems() {
      const fIds = this.queryParams.fId;
      if (fIds !== null) {
        this.$confirm("是否确认导出所有计费物资明细数据?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return exportWarehousebillsitems(fIds);
          })
          .then((response) => {
            this.download(response.msg);
          });
      } else {
        this.$message("请先保存");
      }
    },
    //列设置全选
    allChecked() {
      if (this.allCheck == true) {
        this.setRowList.map((e) => {
          return (e.checked = 0);
        });
      } else {
        this.setRowList.map((e) => {
          return (e.checked = 1);
        });
      }
    },
    //查询列数据
    getRow() {
      let that = this;
      this.data = {
        tableName: "申请费用",
        userId: Cookies.get("userName"),
      };
      select(this.data).then((res) => {
        if (res.data.length != 0) {
          this.getRowList = res.data.filter((e) => e.checked == 0);
          this.setRowList = res.data;
          this.setRowList = this.setRowList.reduce((res, item) => {
            res.push({
              surface: item.surface,
              label: item.label,
              name: item.name,
              checked: item.checked,
              width: item.width,
              fixed: item.fixed,
            });
            return res;
          }, []);
        }
      });
    },
    //保存列设置
    save() {
      this.showSetting = false;
      this.data = {
        tableName: "收费",
        userId: Cookies.get("userName"),
        sysTableSetList: this.setRowList,
      };
      addSet(this.data).then((res) => {
        this.getRowList = this.setRowList.filter((e) => e.checked == 0);
      });
    },
    //重置列表
    delRow() {
      this.data = {
        tableName: "收费",
        userId: Cookies.get("userName"),
      };
      resetModule(this.data).then((res) => {
        if (res.code == 200) {
          this.showSetting = false;
          this.setRowList = this.tableDate;
          this.getRowList = this.tableDate;
        }
      });
    },
    //开始拖拽事件
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd() {
      this.drag = false;
    },

    //收费页面合计
    listTotal(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
        } else if (index === 5|| index === 13) {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          }
        }
      });
      return sums;
    },
    // 查看按钮
    check(row, status) {
      console.log(status)
      let res = {
        fId:row.fId,
        Num:status
      }
      this.$router.push({
        path:'/applyForInvoice/feeDetail',
        query: { data: res }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.totAL = 0;
      this.ids = selection.map((item) => item.fId);
      this.single =
        selection.length !== 1 ||
        selection.map((item) => item.fBillstatus) == 6 ||
        selection.map((item) => item.fBillstatus) == 4;
      this.multiple = !selection.length;
    },
    timeMethods(){
      this.queryParams.applyTime[0] = this.queryParams.applyTime[0]+" 00:00:00"
      this.queryParams.applyTime[1] = this.queryParams.applyTime[1]+" 23:59:59"
    },
    /** 查询财务数据主列表 */
    getList() {
      this.loading = true;
      this.queryParams.money = [this.moneys,this.moneye]
      console.log(this.queryParams)
      listCorps(this.queryParams).then((response) => {
          this.chargeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.getList();
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fId: null,
        fBillno: null,
        fCtrlcorpid: null,
        fCorpid: null,
        tMblno: null,
        fAmtdr: null,
        fAmtcr: null,
        fBilltype: null,
        fBillstatus: "0",
        fRemarks: null,
        fAccbilldate: null,
        delFlag: null,
        createBy: null,
        fDeptid: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("ta");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 远程模糊查询用户 */
    corpsRemoteMethod(name) {
      if (name == null || name === "") {
        return false;
      }
      let queryParams = { fName: name };
      listCorps(queryParams).then((response) => {
        this.fMblnoOptions = response;
        this.KHblnoOptions = response;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.tableFilter = {
        pageNum: 1,
        pageSize: 10,
        fBillno: null,
        fCtrlcorpid: null,
        fCorpid: null,
        timeInterval: null,
      };
      this.handleQuery();
    },
    // 远程模糊查询费用名称
    fWRemoteMethod(name) {
      this.fWbuOptions = [];
      if (name == null || name === "") {
        return false;
      }
      let queryParams = { pageNum: 1, pageSize: 10, fName: name };
      listFees(queryParams).then((response) => {
        this.fWbuOptions = response.rows;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({path:'/applyForInvoice/feeDetail'})
    },
    /** 修改按钮操作 */
    handleUpdate(row,status) {
      console.log(row)
      console.log(status)
      let res = {
        fId:row.fId,
        Num:status
      }
      this.$router.push({
        path:'/applyForInvoice/feeDetail',
        query:{ data : res }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fIds = row.fId || this.ids;
      let tips = "";
      if (Cookies.get("sysType") == 1) {
        //大木
        delCharge_s(fIds).then((data) => {
          switch (data.msg) {
            case "0": {
              this.$message.error("当前数据已被其他操作员操作请刷新页面");
              break;
            }
            case "1": {
              tips = "当前主表有数据从表无数据是否删除";
              this.delete_S(fIds, tips);
              break;
            }
            case "2": {
              tips = "当前主表有数据从表有数据是否删除";
              this.delete_S(fIds, tips);
              break;
            }
            default: {
              return this.$message.error("未知错误，无状态");
            }
          }
        });
      } else if (Cookies.get("sysType") == 2) {
        // 车队;
        delCharge_ss(fIds).then((data) => {
          switch (data.msg) {
            case "0": {
              this.$message.error("当前数据已被其他操作员操作请刷新页面");
              break;
            }
            case "1": {
              tips = "当前主表有数据从表无数据是否删除";
              this.delete_S(fIds, tips);
              break;
            }
            case "2": {
              tips = "当前主表有数据从表有数据是否删除";
              this.delete_S(fIds, tips);
              break;
            }
            default: {
              return this.$message.error("未知错误，无状态");
            }
          }
        });
      }
    },
    delete_S(fIds, tips) {
      this.$confirm(tips, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          if (Cookies.get("sysType") == 1) {
            return delCharge(fIds);
          } else if (Cookies.get("sysType") == 2) {
            return delCharges(fIds);
          }
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有财务数据主数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportCharge(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    //清空一行
    deleteRow(index, rows) {
      this.queryParams.fAmtcr = 0;
      this.queryParams.fAmtdr = 0;
      rows.splice(index, 1);

    },
  },
};
</script>
<style lang="scss" scoped>
.tabSetting {
  display: flex;
  justify-content: flex-end;
}
.listStyle {
  display: flex;
  border-top: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  border-right: 1px solid #dcdfe6;
}
.listStyle:last-child {
  border-bottom: 1px solid #dcdfe6;
}
.progress {
  display: flex;
  align-items: center;
  padding: 2px;
  background-color: rgba(0, 0, 0, 0.05);
  height: 100%;
}
.avue-crud__dialog__header {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}
.el-dialog__title {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  word-wrap: break-word;
}
.avue-crud__dialog__menu {
  padding-right: 20px;
  float: left;
}
.avue-crud__dialog__menu i {
  color: #909399;
  font-size: 15px;
}
.el-icon-full-screen {
  cursor: pointer;
}
.el-icon-full-screen:before {
  content: "\e719";
}
</style>
<style lang="scss">
.el-table {
  .el-table__body-wrapper {
    z-index: 2;
  }
}
</style>
