<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>
        <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
        >
      </slot>
    </lx-header>

    <xy-table :list="list" :table-item="table">
      <template v-slot:btns>
        <el-table-column
          label="操作"
          fixed="right"
          width="300"
          header-align="center"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.status === 0 && type == 1 && scope.row.flow_status === 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
              v-if="false"
              size="small"
              type="primary"
              style="margin-left: 10px; margin-bottom: 4px"
              @click="
                $refs['printRegistration'].getDetailFundLog(scope.row.id),
                  ($refs['printRegistration'].isShow = true)
              "
              >打印</Button
            >
            <Button
              v-if="!scope.row.flow_id"
              size="small"
              type="primary"
              style="margin-left: 10px; margin-bottom: 4px"
              @click="toOutPay(scope.row)"
            >
              支付审批
            </Button>
            <Button
              v-if="scope.row.property && scope.row.property_type_id"
              size="small"
              type="primary"
              style="margin-left: 10px; margin-bottom: 4px"
              @click="toOutAsset(scope.row)"
            >
              资产申请
            </Button>
            <Button v-if="scope.row.flow_id"
                    size="small"
                    type="primary"
                    style="margin-left: 10px; margin-bottom: 4px"
                    @click="toOaDetail(scope.row)">查看</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>

    <!--    oa办理-->
    <Modal
      :width="86"
      class-name="oa-modal"
      title="流程办理"
      fullscreen
      :mask-closable="false"
      v-model="isShowOaModal"
      footer-hide
    >
      <div style="width: 100%;height: 100%;">
        <iframe style="width: 100%;height: 100%;border-radius: 0 0 6px 6px;" :src="oaUrl" frameborder="0"></iframe>
      </div>
    </Modal>
  </div>
</template>

<script>
import { detailContract } from "@/api/contract/contract";
import { fundlogFlow,httpCurl } from "@/api/out";
import { getFundLog, delFundLog } from "@/api/paymentRegistration/fundLog";
import { parseTime } from "@/utils";
import { Message } from "element-ui";
import { show } from "@/api/away"

import printRegistration from "./components/printRegistration";
import detailPaymentRegistration from "./components/detailPaymentRegistration";
import {getToken} from "@/utils/auth";
export default {
  components: {
    printRegistration,
    detailPaymentRegistration,
  },
  data() {
    return {
      isShowOaModal: false,
      oaUrl: '',
      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",
          customFn: row => {
            return (<span>{ row.contract_id ? row.contract.name : row.away.title }</span>)
          }
        },
        {
          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: 330,
          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 && item.plan.pid_info) ? item.plan.pid_info.name: ''} - {item.plan?.name}
                    <br />
                    [使用金额] {item.use_money}元{" "}
                  </div>
                );
              });
            }
          },
        },
        {
          prop: "status",
          label: "审核状态",
          width: 120,
          formatter: (cell, data, value) => {
            if (value === 0) return "待审核";
            else return "已审核";
          },
        },
        {
          prop: 'flow_status',
          label: '流程状态',
          formatter: (cell, data, value) => {
            let map = new Map([
              [1,'待申请'],
              [2,'流转中'],
              [3,'已完成']
            ])
            return map.get(value)
          }
        },
        {
          label: "次数",
          prop: "pay_count",
          width: 95,
          customFn: row => {
            return (<span>{ row.contract_id ? row.pay_count : row.pay_count_away }</span>)
          }
        },
        {
          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: {
    async toOaDetail (row) {
      window.open(
        `${process.env.VUE_APP_OUT_OLD}/flow/view/${row.flow_id}?auth_token=${this.$store.getters.oa_token}`,
        "bidding",
        `top=${this.window.top},left=${this.window.left},width=${this.window.width},height=${this.window.height},location=0`
      )
    },

    async toOutAsset (row) {
      try {
        let flow_id = JSON.parse(row.property_type_detail.remark).flow_id;
        let url = `${process.env.VUE_APP_OUT_OLD}/flow/create/${flow_id}?auth_token=${this.$store.getters.oa_token}`;
        window.open(
          url,
          "signProcess",
          `top=${this.window.top},left=${this.window.left},width=${this.window.width},height=${this.window.height},location=0`
        );
      } catch (e) {

      }
    },
    async toOutPay(row) {
      let payments = [];
      const actNumsTotal = () => {
        let total = 0;
        payments.reduce((pre,cur) => {
          return Number(cur.act_money) ? ++pre : pre;
        },0);
        return total;
      };
      const totalMoney = () => {
        let total = 0.0;
        payments.map((item) => {
          total += Number(item.act_money);
        });
        return total.toFixed(2);
      };
      let contract;
      if (row.contract_id) {
        contract = await detailContract({ id: row.contract_id });
      } else {
        contract = await show({ id: row.away_id });
      }

      payments =
        (
          await getFundLog({
            contract_id: row.contract_id,
            show_type: 1
          })
        )?.data || [];
      console.log(contract);
      let baseInfo = {
        "flow_title": row.contract.name || "",
        "oaUrl": row?.contract?.number,
        "title": row?.contract?.name,
        out_pay_id: row?.id,
        "xiangxishuoming": row?.remark,
        "yifujine": actNumsTotal(),
        "xiangmuzonge": totalMoney(),
        "cishu": payments.length,
        "amt": row?.apply_money,
        "liezhiqudao": contract?.plans.map(i => i.name)?.toString()
      };
      let url = `${process.env.VUE_APP_OUT_OLD}/#/flow/create?auth_token=${window.encodeURIComponent(getToken())}&module_name=oa&isSinglePage=1&module_id=75&out_away_id=${row.id}&default_json=${JSON.stringify(baseInfo)}`;

      this.oaUrl = url;
      this.isShowOaModal = true;
    },

    pageSizeChange(e) {
      this.pageSize = e;
      this.pageIndex = 1;
      this.getFundLogs();
    },
    pageChange(e) {
      this.pageIndex = e;
      this.getFundLogs();
    },

    async getFundLogs(noloading=false) {
      //await fundlogFlow();
      const res = await getFundLog({
        page_size: this.pageSize,
        page: this.pageIndex,
        contract_id: this.contractId,
        keyword: this.keywords,
        date: this.selectDate,
        is_auth: this.is_auth,
        status: this.status,
        show_type: 1
      },noloading);
      this.list = res.data;
      this.total = res.total;
    },

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

    this.getFundLogs();

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

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