<template>
  <div style="padding: 0 20px">
    <lx-header
      icon="md-apps"
      text="付款登记"
      style="margin-bottom: 10px; border: 0px; margin-top: 15px"
    >
      <div slot="content"></div>
      <slot>
        <span style="padding: 0 6px; word-break: keep-all">创建日期</span>
        <span>
          <DatePicker
            :value="selectDate"
            placeholder="请选择日期"
            type="date"
            placement="bottom-start"
            style="width: 180px"
            @on-change="(e) => (selectDate = e)"
          ></DatePicker>
        </span>

        <span style="padding: 0 6px; word-break: keep-all">关键字</span>
        <span>
          <Input
            v-model="keywords"
            placeholder="请输入关键字"
            style="width: 180px"
          ></Input>
        </span>
        <span style="padding: 0 6px; word-break: keep-all"> 状态 </span>
        <Select
          v-model="status"
          clearable
          placeholder="请选择"
          style="width: 100px"
        >
          <Option
            v-for="item in [
              { label: '待审核', value: 0 },
              { label: '已审核', value: 1 },
            ]"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </Option>
        </Select>

        <span style="padding: 0 6px; word-break: keep-all">预算计划</span>

        <span>
          <Input
            v-model="select.plan_name"
            clearable
            placeholder="请选择预算计划"
            @on-focus="showPlanForSearch"
            style="width: 200px"
            @on-clear="clearSelectForSearch"
          />
        </span>

        <Button
          type="primary"
          style="margin-left: 10px"
          ghost
          @click="
            (contractId = ''),
              (pageIndex = 1),
              (keywords = ''),
              (selectDate = '')
          "
          >重置</Button
        >
        <Button type="primary" style="margin-left: 10px" @click="getFundLogs(false)"
          >查询</Button
        >
        <Button type="primary" @click="toExport()" style="margin-left: 10px"
        >导出</Button
        >
      </slot>
    </lx-header>

    <xy-table :list="list" :table-item="table">
      <template v-slot:btns>
        <el-table-column
          label="操作"
          fixed="right"
          width="200"
          header-align="center"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.status === 0 && type == 1">
              <Poptip
                placement="bottom"
                confirm
                :transfer="true"
                title="确认要删除吗"
                @on-ok="deleteFundLog(scope.row)"
              >
                <Button
                  size="small"
                  type="error"
                  style="margin-left: 10px; margin-bottom: 4px"
                  ghost
                  >删除</Button
                >
              </Poptip>

              <Button
                size="small"
                type="primary"
                style="margin-left: 10px; margin-bottom: 4px"
                @click="
                  $refs['detailPaymentRegistration'].getFundLog(scope.row.id),
                    ($refs['detailPaymentRegistration'].isShow = true)
                "
                >编辑</Button
              >
            </template>
            <Button
              size="small"
              type="primary"
              style="margin-left: 10px; margin-bottom: 4px"
              @click="
                $refs['printRegistration'].getDetailFundLog(scope.row.id),
                  ($refs['printRegistration'].isShow = true)
              "
              >打印</Button
            >
          </template>
        </el-table-column>
      </template>
    </xy-table>

    <div style="display: flex; justify-content: flex-end">
      <Page
        :total="total"
        show-elevator
        @on-change="pageChange"
        show-sizer
        @on-page-size-change="pageSizeChange"
      />
    </div>

    <printRegistration ref="printRegistration"></printRegistration>

    <detailPaymentRegistration
      ref="detailPaymentRegistration"
      @success="getFundLogs"
    ></detailPaymentRegistration>

    <!--  搜索使用 预算计划  -->
    <xy-dialog
      :is-show.sync="isShowPlanForSearch"
      title="预算计划"
      :width="720"
      @on-ok="planSelectForSearch"
    >
      <template v-slot:normalContent>
        <Input
          v-model="planSearch.name"
          search
          enter-button="搜 索"
          placeholder="搜索预算计划.."
          @on-search="searchBudgets"
        />
        <div
          style="
            margin: 10px 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div>
            已选择：<span style="margin-right: 10px">{{
              select.plan_name
            }}</span>
          </div>
          <el-link type="success" @click="clearSelectForSearch"
            >清空选择</el-link
          >
        </div>
        <xy-table
          :list="plans"
          @rowClick="selectPlanForSearch"
          :show-index="false"
          :table-item="planTableSearch"
          :height="310"
          style="margin-top: 10px"
          ref="singlePlanTable"
        >
          <template v-slot:btns> </template>
        </xy-table>

        <div style="display: flex; justify-content: flex-end">
          <Page :total="planTotal" show-elevator @on-change="planPageChange" />
        </div>
        <el-tag type="warning">点击行进行选择</el-tag>
      </template>

      <template v-slot:footerContent>
        <Button type="primary" @click="confirmPlanForSearch">确定</Button>
      </template>
    </xy-dialog>
  </div>
</template>

<script>
import { getFundLog, delFundLog } from "@/api/paymentRegistration/fundLog";
import { parseTime } from "@/utils";
import { Message } from "element-ui";

import printRegistration from "./components/printRegistration";
import detailPaymentRegistration from "./components/detailPaymentRegistration";
import { getBudget } from "@/api/budget/budget";
import {getparameter} from "@/api/system/dictionary";
import {getToken} from "@/utils/auth";
export default {
  components: {
    printRegistration,
    detailPaymentRegistration,
  },
  data() {
    return {
      select: {
        plan_id: "",
        plan_name: "",
      },
      planSearch: {
        name: "",
        plan_department_id: "",
      },
      plans: [],
      planTotal: 0,
      plan: [],
      moneyWay: [],
      planTableSearch: [
        {
          label: "分类",
          prop: "type",
          formatter: (cell, data, value) => {
            let res = this.moneyWay.filter((item) => {
              return item.id === value;
            });
            return res[0]?.value || "未知";
          },
          width: 170,
        },
        {
          label: "年份",
          prop: "year",
          align: "center",
          width: 100,
        },

        {
          label: "名称",
          prop: "name",
          width: 260,
          align: "left",
        },
        {
          label: "计划金额",
          prop: "money",
          align: "right",
          width: 160,
        },
      ],
      isShowPlanForSearch: false,
      selectDate: "",
      keywords: "",
      list: [],
      contractId: "",
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      is_auth: 1,
      status: "",
      table: [
        {
          label: "项目名称",
          minWidth: 250,
          prop: "contract.name",
          align: "left",
          fixed: "left",
        },
        {
          label: "付款申请金额(元)",
          prop: "apply_money",
          align: "right",
          width: 180,
          formatter: (v1, v2, value) => {
            return Number(value)
              .toFixed(2)
              .replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
          },
        },
        {
          label: "实际支付金额(元)",
          prop: "act_money",
          align: "right",
          width: 180,
          formatter: (v1, v2, value) => {
            return Number(value)
              .toFixed(2)
              .replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
          },
        },
        {
          label: "款项类型",
          prop: "type",
          width: 120,
        },
        {
          label: "预算计划",
          width: 320,
          align: "left",
          customFn: (row) => {
            {
              if (row.act_plan_link.length > 0) {
                return row.act_plan_link.map((item) => {
                  return (
                    <div>
                      {" "}
                      [{item.plan.year}] - {item.plan.name} <br /> [使用金额]{" "}
                      {item.use_money}元{" "}
                    </div>
                  );
                });
              }
            }
          },
        },
        {
          prop: "status",
          label: "状态",
          width: 120,
          formatter: (cell, data, value) => {
            if (value === 0) return "待审核";
            else return "已审核";
          },
        },
        {
          label: "次数",
          prop: "pay_count",
          width: 95,
          formatter: (cell, data, value) => {
            return value + 1;
          },
        },
        {
          label: "是否为最后一笔",
          prop: "is_end",
          width: 145,
          formatter: (cell, data, value) => {
            return value == 1 ? "是" : "否";
          },
        },
        {
          label: "经办人",
          minWidth: 160,
          prop: "admin.name",
          align: "center",
        },
        {
          label: "业务科室",
          minWidth: 160,
          prop: "department.name",
          align: "center",
        },
        {
          label: "备注",
          minWidth: 460,
          prop: "remark",
          align: "left",
        },
        {
          label: "创建信息",
          prop: "created_at",
          width: 160,
          formatter: (cell, data, value) => {
            return parseTime(new Date(value), "{y}-{m}-{d}");
          },
        },
      ],
    };
  },
  methods: {
    toExport() {
      this.is_export = 1;
      this.getFundLogs(true);
    },

    //获取资金渠道
    async getMoneyWay() {
      this.moneyWay = (
        await getparameter({
          number: "money_way",
        })
      ).detail;
    },
    planPageChange(e) {
      this.plansPageIndex = e;
      this.getBudgets();
    },
    confirmPlanForSearch() {
      this.isShowPlanForSearch = false;
      this.getFundLogs();
    },
    async showPlanForSearch() {
      this.isShowPlanForSearch = true;
      await this.getBudgets();
    },
    //确认计划选择搜索
    planSelectForSearch() {
      if (this.select.plan_id == "") {
        Message({
          type: "warning",
          message: "选择计划不能为空",
        });
        return;
      }
      this.isShowPlanForSearch = false;
    },
    //计划搜索
    searchBudgets() {
      this.plansPageIndex = 1;
      this.getBudgets();
    },
    //选择计划 搜索
    selectPlanForSearch(sel) {
      console.log(sel);
      if (sel) {
        this.select.plan_id = sel.id;
        this.select.plan_name = "[" + sel.year + "]-" + sel.name;
      } else {
        this.select.plan_id = "";
        this.select.plan_name = "";
      }
    },

    //获取预算计划
    async getBudgets() {
      await getBudget({
        name: this.planSearch.name,
        page_size: 10,
        page: this.plansPageIndex,
        plan_department_id: this.planSearch.plan_department_id,
        top_pid: 1,
      }).then((res) => {
        this.plans = res.list.data;

        this.planTotal = res.list.total;

        this.toggleSelection(
          this.plan.map((item) => {
            return item.value.plan_id;
          }),
          1
        );
      });
    },
    //默认选择计划
    toggleSelection(plans, type) {
      if (plans) {
        this.plans
          .filter((plan) => {
            if (plans.includes(plan.id)) {
              plan.useMoney = this.plan[plans.indexOf(plan.id)].value.use_money;
              return true;
            }
          })
          .map((row) => {
            this.$refs.planTable.toggleRowSelection(row);
          });
      } else {
        this.$refs.planTable.clearSelection();
      }
    },
    clearSelectForSearch() {
      this.select.plan_id = "";
      this.select.plan_name = "请选择预算计划";
    },
    pageSizeChange(e) {
      this.pageSize = e;
      this.pageIndex = 1;
      this.getFundLogs();
    },
    pageChange(e) {
      this.pageIndex = e;
      this.getFundLogs();
    },

    async getFundLogs(is_export) {
      await getFundLog({
        page_size: this.pageSize,
        page: this.pageIndex,
        keyword: this.keywords,
        date: this.selectDate,
        status: this.status,
        act_plan_link_id: this.select.plan_id,
      }).then((res) => {
        let tokens = getToken();
        if (is_export) {
          var url = "/api/admin/fund_log/index?token=" + tokens;
          if (this.selectDate) url += "&date=" + this.selectDate;
          if (this.keywords) url += "&keyword=" + this.keywords;
          if (typeof this.status != "undefined")
            url += "&status=" + this.status;
          if (this.select.plan_id)
            url += "&act_plan_link_id=" + this.select.plan_id;
          url += "&is_export=" + 1;
          url = location.host + url;
          console.log(url);
          window.open("http://" + url, "_blank");
          return;
        }
        this.list = res.data;
        this.total = res.total;
      });
    },

    deleteFundLog(row) {
      delFundLog({
        id: row.id,
      }).then((res) => {
        Message({
          type: "success",
          message: "操作成功",
        });
        this.getFundLogs();
      });
    },
  },
  mounted() {
    this.contractId = this.$route.query.contractId;

    this.getFundLogs();
  },
  created() {
    let type = parseInt(this.$route.path.split("_")[1]);
    this.type = this.is_auth = type;
    this.getMoneyWay();
  },
};
</script>

<style scoped lang="scss"></style>
