<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%"
          @change="radioChange"
        >
          <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%" value-format="yyyy-MM-dd" v-model="form.startTime"></el-date-picker>
          </el-col>
          <el-col :span="4">
            <el-date-picker placeholder="结束时间" style="width:100%" value-format="yyyy-MM-dd" 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-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 customerSelectData"
            :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 providerSelectData"
            :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="inline-btn">
      <div class="totalSumDiv">全部金额合计：{{totalSum}}</div>
      <div class="downloadBtn" v-if="searchResult.length !== 0">
        <el-button type="primary" @click="onDownload">下载本表</el-button>
      </div>
    </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,
  downloadData
} 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: "",
        endTime: "",
        minAmount: "",
        maxAmount: "",
        isEntry: false,
        pageNo: 1,
        pageSize: 50
      },
      pageNo: 1,
      pageSize: 50,
      totalNumber: 0,
      formLabelWidth: "120px",
      teamSelectData: [],
      projectSelectData: [],
      productSelectData: [],
      costTeamSelectData: [],
      costTypeSelectData: [],
      providerSelectData: [],
      customerSelectData: [],
      manageData: [],
      companyData: [],
      tableType: "",
      isIndeterminate: true,
      checkAll: false,
      totalSum: 0, // 后台返回的合计
      incomeStatus: [
        { name: "开票/应收", id: "INVOICE" },
        { name: "到账", id: "ARRIVAL" },
        { name: "内部核算", id: "INTERNAL" }
      ]
    };
  },
  created() {
    // 获取部门下拉框
    getTeamSelect("COMPANY").then(res => {
      this.teamSelectData = res.data;
    });
    // 获取项目下拉框
    getProjectSelect().then(res => {
      this.projectSelectData = res.data;
    });
    //获取产品下拉框
    getProductSelect().then(res => {
      this.productSelectData = res.data;
    });
    //获取供应商下拉
    getTeamSelect("OTHERS").then(res => {
      this.providerSelectData = res.data;
    });
    //获取客户下拉
    getTeamSelect("PARTNER").then(res => {
      this.customerSelectData = res.data;
    });
    //获取成本类型下拉
    getCostTypeSelect().then(res => {
      this.costTypeSelectData = res.data;
    });
  },

  methods: {
    // 收入或成本变化时 清空一些条件
    radioChange() {
      this.form.toDeptId = "";
      this.form.incomeStatus = [];
      this.form.productId = [];
      this.form.costTypeId = [];
    },
    // 下载表格
    onDownload() {
      //  this.form.startTime = this.form.startTime === null ? '' : typeof this.form.startTime === 'object'  ? this.form.startTime.toString() : this.form.startTime;
      // this.form.endTime = this.form.endTime === null ? '' : typeof this.form.endTime === 'object'  ? this.form.endTime.toString() : this.form.endTime;
      let url = "http://manage.ai160.com/manageBase/manage/export?";
      for (let key in this.form) {
        let str = key + "=" + this.form[key] + "&";
        url += str;
      }
      window.open(url.slice(0, -1));
    },
    // 自定义合计
    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"]));
            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 += "";
      num = num.replace(/^-/,'');
      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.tableType = "INCOME";
      }
      if (this.form.type === "COST") {
        this.tableType = "COST";
      }
      this.form.pageNo = 1;

      this.$post("manageBase/manage/search", this.form).then(response => {
        if (response.data && response.data.length == 0) {
          this.totalSum = 0;
          this.$message("未找到相应数据");
          return;
        }
        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
        );
      });
    },
    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; */
}
.inline-btn {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 80px;
  width: 500px;
}
</style>