<template>
  <div class="paddingLeft">
    <!-- <TitleBar propTitle="经营数据查询" /> -->
    <el-form :model="form" ref="form" class="marginTop">
      <el-form-item label="查询类别" :label-width="formLabelWidth">
        <el-radio-group
          v-model="form.type"
          placeholder="请选择类别"
          size="medium"
          :rules="[{ required: true, message: '必选'}]"
          style="width:100%"
        >
          <el-row :gutter="10">
            <el-col :span="4">
              <el-radio border style="width:100%;" label="INCOME">收入</el-radio>
            </el-col>
            <el-col :span="4">
              <el-radio border style="width:100%;" label="COST">成本</el-radio>
            </el-col>
          </el-row>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="时间范围" v-if="form.type!==''" :label-width="formLabelWidth">
        <el-row :gutter="10">
          <el-col :span="4">
            <el-date-picker placeholder="起始时间" style="width:100%" v-model="form.startTime"></el-date-picker>
          </el-col>
          <el-col :span="4">
            <el-date-picker placeholder="结束时间" style="width:100%" v-model="form.endTime"></el-date-picker>
          </el-col>
        </el-row>
      </el-form-item>
      <!-- <el-form-item label="金额范围" v-if="form.type!==''" :label-width="formLabelWidth">
        <el-row :gutter="10">
          <el-col :span="4">
            <el-input placeholder="起始金额" style="width:100%" v-model="form.minAmount" clearable></el-input>
          </el-col>
          <el-col :span="4">
            <el-input placeholder="结束金额" style="width:100%" v-model="form.maxAmount" clearable></el-input>
          </el-col>
        </el-row>
      </el-form-item>-->
      <el-form-item
        label="成本类型"
        v-if="form.type==='COST'"
        prop="costTypeId"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.costTypeId" multiple placeholder="全选" ref="select">
          <el-option
            v-for="item in costTypeSelectData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收入状态" v-if="form.type==='INCOME'" :label-width="formLabelWidth">
        <el-select v-model="form.incomeStatus" multiple placeholder="全选">
          <el-option
            v-for="item in incomeStatus"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>

        <!-- <el-row :gutter="10">
          <el-col :span="1">
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              size="medium"
            >全选</el-checkbox>
          </el-col>

          <el-checkbox-group
            style="width:100%"
            v-model="form.incomeStatus"
            placeholder="请选择状态值"
            size="medium"
            :indeterminate="isIndeterminate"
          >
            <el-col :span="4">
              <el-checkbox style="width:100%;" border label="INVOICE">开票/应收</el-checkbox>
            </el-col>
            <el-col :span="4">
              <el-checkbox style="width:100%;" border label="ARRIVAL">到账</el-checkbox>
            </el-col>
            <el-col :span="4">
              <el-checkbox style="width:100%;" border label="INTERNAL">内部核算</el-checkbox>
            </el-col>
          </el-checkbox-group>
        </el-row>-->
      </el-form-item>
      <el-form-item
        label="归属产品"
        v-if="form.type==='INCOME'"
        prop="productId"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.productId" multiple placeholder="全选">
          <el-option
            v-for="item in productSelectData"
            :key="item.id"
            :label="item.code +'--'+ item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="归属项目"
        v-if="form.type!==''"
        prop="projectId"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.projectId" multiple placeholder="全选">
          <el-option
            v-for="item in projectSelectData"
            :key="item.id"
            :label="item.code +'--'+ item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="归属部门"
        prop="deptId"
        multiple
        v-if="form.type!==''"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.deptId" multiple placeholder="全选" ref="select">
          <el-option
            v-for="item in teamSelectData"
            :key="item.id"
            :label="item.code +'--'+ item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="来源项目"
        prop="toProjectId"
        v-if="form.type==='INCOME'"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.toProjectId" multiple placeholder="全选">
          <el-option
            v-for="item in projectSelectData"
            :key="item.id"
            :label="item.code +'--'+ item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="来源部门"
        prop="toDeptId"
        v-if="form.type==='INCOME'"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.toDeptId" multiple placeholder="全选" ref="select">
          <el-option
            v-for="item in teamSelectData"
            :key="item.id"
            :label="item.code +'--'+ item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="接收项目"
        prop="toProjectId"
        v-if="form.type==='COST'"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.toProjectId" multiple placeholder="全选">
          <el-option
            v-for="item in projectSelectData"
            :key="item.id"
            :label="item.code +'--'+ item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="接收部门"
        prop="toDeptId"
        v-if="form.type==='COST'"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.toDeptId" multiple placeholder="全选" ref="select">
          <el-option
            v-for="item in teamSelectData"
            :key="item.id"
            :label="item.code +'--'+ item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="position: absolute; width:23%; left:300px;">
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <!-- <el-button type="info" @click="onReset">重置</el-button> -->
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="info" @click="reset">重置</el-button>
      </el-form-item>-->
    </el-form>
    <!-- 查询结果收入表 -->
    <div class="totalSumDiv">全部金额合计：{{totalSum}}</div>
    <el-table
      :data="searchResult"
      style="margin-top:30px;"
      :summary-method="tableSummary"
      show-summary
      v-if="tableType === 'INCOME'"
      border
    >
      <el-table-column
        prop="happenTime"
        width="120px"
        align="right"
        :formatter="dateFormat"
        label="发生日期"
      ></el-table-column>
      <el-table-column
        :formatter="moneyFormat"
        prop="amount"
        width="130px"
        align="right"
        label="金额"
      ></el-table-column>
      <el-table-column
        label="收入状态"
        width="130px"
        align="right"
        prop="incomeStatus"
        :formatter="incomeTypeFormat"
      ></el-table-column>
      <el-table-column label="产品" width="200px" align="right" prop="product.name"></el-table-column>
      <el-table-column label="归属项目" width="235px" align="right" prop="project.name"></el-table-column>
      <el-table-column label="归属部门" width="250px" align="right" prop="department.name"></el-table-column>
      <el-table-column label="来源项目" width="235px" align="right" prop="toProject.name"></el-table-column>
      <el-table-column label="来源部门" width="300px" align="right" prop="toDepartment.name"></el-table-column>
      <el-table-column prop="remark" min-width="300px" align="right" label="备注"></el-table-column>
      <el-table-column
        width="120px"
        align="right"
        label="录入日期"
        :formatter="recordTimeFormat"
        prop="gmtModife"
      ></el-table-column>
    </el-table>

    <!-- 查询结果成本表 -->
    <el-table
      :data="searchResult"
      style="margin-top:30px;"
      show-summary
      :summary-method="tableSummary"
      v-if="tableType === 'COST'"
      border
    >
      <el-table-column
        prop="happenTime"
        width="120px"
        align="right"
        :formatter="dateFormat"
        label="发生日期"
      ></el-table-column>
      <el-table-column
        :formatter="moneyFormat"
        prop="amount"
        width="130px"
        align="right"
        label="金额"
      ></el-table-column>
      <el-table-column label="成本类别" width="270px" align="right" prop="costType.name"></el-table-column>
      <el-table-column label="发生部门" width="240px" align="right" prop="department.name"></el-table-column>
      <el-table-column label="发生项目/人" width="245px" align="right" prop="project.name"></el-table-column>
      <el-table-column label="接收项目" width="235px" align="right" prop="toProject.name"></el-table-column>
      <el-table-column label="接收部门" width="310px" align="right" prop="toDepartment.name"></el-table-column>
      <el-table-column label="备注"  min-width="300px" align="right" prop="remark"></el-table-column>
      <el-table-column
        width="120px"
        align="right"
        label="录入日期"
        :formatter="recordTimeFormat"
        prop="gmtModife"
      ></el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      @current-change="handlePageChange"
      :page-size="50"
      :current-page.sync="pageNo"
      layout="prev, pager, next"
      v-if="searchResult && searchResult.length!==0"
      :total="totalNumber"
    ></el-pagination>
  </div>
</template>
<script>
import {
  getTeamSelect,
  getProjectSelect,
  getProductSelect,
  getCostTeamSelect,
  getCostTypeSelect,
  addManage,
  getManageList,
  setManage
} from "@/api/manageApi";
import TitleBar from "../layout/titleBar/TitleBar.vue";
import { formatTime } from "../../utils/common";
const statusOptions = ["INVOICE", "ARRIVAL", "INTERNAL"];
export default {
  components: {
    TitleBar
  },
  data() {
    return {
      type: "",
      dialogFormVisible: false,
      addFlag: false,
      id: "",
      searchResult: [],
      form: {
        type: "INCOME",
        productId: [],
        projectId: [],
        toDeptId: "",
        toProjectId: "",
        deptId: [],
        incomeStatus: [],
        status: "NORMAL",
        costTypeId: [],
        startTime: null,
        endTime: null,
        minAmount: "",
        maxAmount: "",
        isEntry: false,
        pageNo: 1,
        pageSize: 50
      },
      pageNo: 1,
      pageSize: 50,
      totalNumber: 0,
      formLabelWidth: "120px",
      teamSelectData: [],
      projectSelectData: [],
      productSelectData: [],
      costTeamSelectData: [],
      costTypeSelectData: [],
      manageData: [],
      companyData: [],
      tableType: "",
      isIndeterminate: true,
      checkAll: false,
      totalSum: 0, // 后台返回的合计
      incomeStatus: [
        { name: "开票/应收", id: "INVOICE" },
        { name: "到账", id: "ARRIVAL" },
        { name: "内部核算", id: "INTERNAL" }
      ]
    };
  },
  created() {
    // 获取部门下拉框
    getTeamSelect().then(res => {
      this.teamSelectData = res.data;
    });
    // 获取项目下拉框
    getProjectSelect().then(res => {
      this.projectSelectData = res.data;
    });
    //获取产品下拉框
    getProductSelect().then(res => {
      this.productSelectData = res.data;
    });
    //获取经营列表
    // getManageList({
    //   type: "INCOME"
    // }).then(res => {
    //   this.manageData = res.data;
    //   console.log(res.data);
    // });
    //获取单位下拉
    getCostTeamSelect().then(res => {
      this.costTeamSelectData = res.data;
    });
    //获取成本类型下拉
    getCostTypeSelect().then(res => {
      this.costTypeSelectData = res.data;
    });
  },

  methods: {
    // 自定义合计
    tableSummary(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        switch (column.property) {
          case "happenTime":
            sums[index] = "本页合计";
            break;
          // case "happenTime":
          //   sums[index] = "";
          //   break;
          case "amount":
            const amountNum = data.map(item => Number(item["amount"]));
            console.log(amountNum);
            let amountTemp = amountNum.reduce((prev, cur) => {
              // const sum = prev.toFixed(2) + cur.toFixed(2);
              return (parseFloat(prev) + parseFloat(cur)).toFixed(2);
            }, 0);
            sums[index]  = this.moneyFormatNew(amountTemp);
            break;
          case "remark":
            sums[index] = "全部合计:";
            break;
          case "gmtModife":
            sums[index] = this.totalSum;
            break;
          default:
            break;
        }
      });
      return sums;
    },
    // 金额格式化
    moneyFormat(row) {
      let num = row.amount.toFixed(2);
      num += "";
      return num.replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
        return $1 + ",";
      });
    },
    // 重写一遍 方便接收参数
    moneyFormatNew(amount) {
      let num = parseFloat(amount).toFixed(2);
      num += "";
      return num.replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
        return $1 + ",";
      });
    },
    // 全选
    handleCheckAllChange(val) {
      this.form.incomeStatus = val ? statusOptions : [];
      this.isIndeterminate = false;
      this.checkAll = val;
    },
    handlePageChange(val) {
      this.form.pageNo = val;
      this.$post("manageBase/manage/search", this.form).then(response => {
        this.searchResult = response.data.content;
        this.totalNumber = parseInt(response.data.totalElements);
        this.pageNo = parseInt(response.data.number) + 1;
        if (response.data && response.data.length == 0) {
          this.$message("未找到相应数据");
        }
      });
    },
    onSubmit() {
      // this.totalNumber = 0;
      this.searchResult = [];
      if (this.form.type === "INCOME") {
        this.form.costTypeId = "";
        this.tableType = "INCOME";
      }
      if (this.form.type === "COST") {
        this.form.incomeStatus = "";
        this.form.productId = "";
        this.tableType = "COST";
      }
      this.form.pageNo = 1;
      this.$post("manageBase/manage/search", this.form).then(response => {
        this.searchResult = response.data.content;
        this.totalNumber = parseInt(response.data.totalElements);
        this.pageNo = parseInt(response.data.number) + 1;
        this.totalSum = this.moneyFormatNew(response.data.content[0].totalAmount)
        console.log("全部合计", response.data.content[0].totalAmount);
        if (response.data && response.data.length == 0) {
          this.$message("未找到相应数据");
        }
      });
    },
    onReset() {
      this.form.type = "";
      this.form.costTypeId = "";
      this.tableType = "";
      this.searchResult = "";
      this.$refs.form.resetFields();
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.type === "COST") {
        return "cost-row-search";
      } else {
        return "income-row-search";
      }
      // return "";
    },
    //获取部门名称
    getName(val) {
      let obj = {};
      obj = this.teamSelectData.find(item => {
        return item.id === val;
      });
      let getName = "";
      this.form.deptName = obj.name;
    },
    // 添加
    append(type) {
      this.type = type;
      this.dialogFormVisible = true;
      this.addFlag = true;
    },
    // 格式化时间
    dateFormat(row, column) {
      return formatTime(row.happenTime);
    },
    recordTimeFormat(row) {
      return formatTime(row.gmtModified);
    },
    incomeTypeFormat(row) {
      return row.incomeStatus == "INVOICE"
        ? "开票/应收"
        : row.incomeStatus == "ARRIVAL"
        ? "到账"
        : "内部核算";
    }
  }
};
</script>

<style scope>
.paddingLeft {
  padding: 0 20px 0 20px;
}
.marginTop {
  margin-top: 20px;
}
.el-table .cost-row-search {
  /* color: green; */
  /* background: #f0f9eb; */
  color: green;
}

.el-table .income-row-search {
  /* color: red; */
  /* background: rgba(248, 181, 172, 0.267); */
  color: red;
  /* color: #f0f9eb; */
}
.totalSumDiv {
  width: 100%;
  /* text-align: right; */
  padding-left: 120px;
  display: block;
  margin-top: 80px;
}
</style>