<template>
  <div class="capitalClaim pagePadding">
    <div
      v-if="powers && powers.length > 0 && powers.some((item) => item == '001')"
    >
      <el-row :gutter="10" style="padding-bottom: 10px">
        <el-col :span="8" style="width: 440px">
          <el-select
            v-model="code"
            multiple
            filterable
            :size="searchSize"
            remote
            style="width: 100%"
            :multiple-limit="1"
            reserve-keyword
            placeholder="认领公司名称"
            :remote-method="remoteMethod"
            :loading="selectLoading"
            class="setWidth"
          >
            <el-option
              v-for="item in activeOptions"
              :key="item.companyNo"
              :label="item.companyName"
              :value="item.companyNo"
            />
          </el-select>
        </el-col>
        <el-col :span="8" style="width: 312px">
          <el-input :size="searchSize" v-model="input" placeholder="关键字">
            <el-select
              style="width: 103px"
              v-model="select"
              slot="prepend"
              placeholder="请选择"
            >
              <el-option label="资金编码" value="1"></el-option>
              <el-option label="付款方" value="2"></el-option>
            </el-select>
            <!-- <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchList"
            ></el-button> -->
          </el-input>
        </el-col>
        <el-col :span="3" style="width: 216px" class="fr tr">
          <el-button
            v-if="powers.some((item) => item == '023')"
            :size="searchSize"
            type="primary"
            :disabled="downLoading"
            @click="dlTemplate"
          >
            下载模板
          </el-button>
          <el-button
            v-if="powers.some((item) => item == '038')"
            :size="searchSize"
            type="primary"
            @click="importshowModel = true"
          >
            导入数据
          </el-button>
        </el-col>
      </el-row>
      <el-row :gutter="10" style="padding-bottom: 10px">
        <el-col :span="7" style="width: 138px">
          <el-select
            style="width: 100%"
            :size="searchSize"
            v-model="parmValue.status"
            clearable
            placeholder="认领状态"
            @change="
              pageInfo.curr = 1;
              parmValue.page = 1;
              searchList();
            "
          >
            <el-option
              v-for="item in capitalFlowType"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-col>

        <el-col :span="6" style="width: 302px">
          <period-date-picker
            :start="parmValue.start"
            :end="parmValue.end"
            :type="1"
            :width="'135px'"
            :size="searchSize"
            @timeReturned="timeReturned($event)"
          />
        </el-col>
        <el-col :span="6" style="width: 302px">
          <number-range
            :start="parmValue.total_low"
            :end="parmValue.total_up"
            :type="1"
            :width="'135px'"
            :title="'资金总额'"
            :size="searchSize"
            @numReturned="numReturned($event, 0)"
          />
        </el-col>

        <el-col :span="4" style="width: 226px" class="fr tr">
          <el-button
            type="primary"
            :size="searchSize"
            icon="el-icon-search"
            @click="searchList"
          />
          <el-button
            type="warning"
            v-if="powers.some((item) => item == '024')"
            :size="searchSize"
            @click="restSearch"
          >
            重置
          </el-button>
          <el-button
            v-if="powers.some((item) => item == '002')"
            :size="searchSize"
            type="primary"
            @click="searchList"
          >
            刷新
          </el-button>
        </el-col>
      </el-row>
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        :size="size"
        row-key="traNo"
        stripe
        style="width: 100%"
        :default-expand-all="false"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          label="资金编号"
          prop="traNo"
          width="220px"
          fixed="left"
        />

        <el-table-column label="收入/支出" prop="trade_type" width="80px">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.trade_type === '0' ? 'success' : 'warning'"
              size="mini"
              v-text="scope.row.trade_type === '0' ? '收入' : '支出'"
            ></el-tag>
          </template>
        </el-table-column>

        <el-table-column label="认领状态" prop="status" width="90px">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status_type"
              size="mini"
              v-text="scope.row.statusName"
            ></el-tag>
          </template>
        </el-table-column>
        <el-table-column label="认领企业编码" prop="companyNo" width="130px" />
        <el-table-column
          label="认领企业"
          show-overflow-tooltip
          prop="companyName"
          min-width="170px"
        />
        <el-table-column label="记录总金额" prop="total_fee" width="120px" />
        <el-table-column label="已认领金额" prop="amount" width="120px" />

        <el-table-column
          label="对方公司"
          prop="trade_out"
          show-overflow-tooltip
          min-width="170px"
        />
        <el-table-column
          label="对方账号"
          prop="trade_account"
          show-overflow-tooltip
          width="170px"
        />

        <el-table-column
          label="付款备注"
          show-overflow-tooltip
          prop="trade_used"
          width="180px"
        />
        <el-table-column
          label="驳回原因"
          show-overflow-tooltip
          prop="exam_remark"
          width="180px"
        />

        <el-table-column label="交易时间" prop="trade_time" width="145px" />
        <el-table-column fixed="right" label="操作" width="85px">
          <template slot-scope="scope">
            <el-tooltip
              v-if="
                (powers.some((item) => item == '039') &&
                  scope.row.logNo === scope.row.traNo &&
                  scope.row.status === '1' &&
                  parseInt(scope.row.balance) !== 0) ||
                (powers.some((item) => item == '039') &&
                  scope.row.logNo === scope.row.traNo &&
                  scope.row.status === '6' &&
                  parseInt(scope.row.balance) !== 0)
              "
               
              effect="dark"
              content="资金认领"
              placement="top"
            >
              <i
                class="el-icon-s-flag tb-icon"
                @click="
                  openModal(
                    scope.row.id,
                    scope.row.traNo,
                    '039',
                    scope.row.exam_remark,
                    scope.row.status,
                    scope.row.trade_type
                  )
                "
              ></i>
            </el-tooltip>
            <el-tooltip
              v-if="
                powers.some((item) => item == '040') &&
                scope.row.logNo !== scope.row.traNo &&
                scope.row.status === '2'
              "
               
              effect="dark"
              content="认领审核"
              placement="top"
            >
              <i
                class="el-icon-s-check tb-icon"
                @click="
                  openModal(
                    scope.row.id,
                    scope.row.traNo,
                    '040',
                    scope.row.exam_remark,
                    scope.row.status
                  )
                "
              ></i>
            </el-tooltip>
            <el-tooltip
              v-if="
                (powers.some((item) => item == '040') &&
                  scope.row.logNo !== scope.row.traNo &&
                  scope.row.status === '2') ||
                (powers.some((item) => item == '040') &&
                  scope.row.logNo !== scope.row.traNo &&
                  scope.row.status === '4')
              "
               
              effect="dark"
              content="取消认领申请"
              placement="top"
            >
              <i
                class="el-icon-error tb-icon"
                @click="changeStatus(scope.row.traNo)"
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div
        class="Pagination"
        style="text-align: right; margin-top: 10px"
        v-show="count > 0"
      >
        <el-pagination
          :size="searchSize"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :current-page="parmValue.page"
          :page-sizes="[15, 50, 100]"
          :page-size="parmValue.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        ></el-pagination>
      </div>
    </div>
    <no-auth v-else></no-auth>
    <add-edit
      :show-model="importshowModel"
      @refresh="searchList"
      @cancel="importshowModel = false"
    />
    <add-edit1
      :id="modelId"
      :show-model="showModel"
      :is-detail="isDetail"
      :logNo="logNo"
      :exam_remark="exam_remark"
      :status="status"
      :trade_type="trade_type"
      @refresh="searchList"
      @cancel="showModel = false"
    />
  </div>
</template>
<script>
import addEdit from "./addEdit";
import addEdit1 from "./addEdit1";
import asyncRequest from "@/apis/service/InvoiceSales/capitalClaim";
import urlConfig from "@/apis/url-config";
import mixinPage from "@/mixins/elPaginationHandle";
import { mapGetters } from "vuex";
import PeriodDatePicker from "@/components/PeriodDatePicker";
import numberRange from "@/components/numberRange";
import { invoiceType, orderType, capitalFlowType } from "@/assets/js/linkType";
import { timestampToTime } from "@/utils/validate";
import resToken from "@/mixins/resToken";
export default {
  name: "capitalClaim",
  mixins: [mixinPage, resToken],
  components: {
    addEdit,
    PeriodDatePicker,
    numberRange,
    addEdit1,
  },

  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "capitalClaim"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  data() {
    return {
      select: "1",
      sname: "",
      stype: "",
      input: "",
      timer: false,
      logNo: "",
      status: "",
      trade_type: "",
      exam_remark: "",
      importshowModel: false,
      fileUrl: urlConfig.baseURL + "%E8%B5%84%E9%87%91%E6%A8%A1%E6%9D%BF.xls",
      invoiceType: invoiceType,
      orderType: orderType,
      capitalFlowType: capitalFlowType,
      downLoading: false,
      code: [],
      selectLoading: false,
      activeOptions: [],
      name: "",
      contector: "",
      loading: false,
      showModel: false,
      isDetail: false,
      modelId: 0,
      parmValue: {
        companyNo: "",
        name: "",
        logNo: "", //
        total_low: "", //
        total_up: "", //
        start: "",
        end: "",
        status: "", //
        page: 1, // 页码
        size: 15, // 每页显示条数
      },
      // 表格 - 数据
      tableData: [],
      count: 0, // 总条数
    };
  },

  mounted() {
    this.searchList();
  },
  methods: {
    restSearch() {
      this.code = [];
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.parmValue = {
        companyNo: "",
        total_low: "", //
        total_up: "", //
        name: "",
        start: "",
        end: "",
        logNo: "", //
        status: "", //
        page: 1, // 页码
        size: 15, // 每页显示条数
      };
      this.searchList();
    },
    // 新建/编辑/详情
    openModal(id, logNo, isDetail, exam_remark, status, trade_type) {
      console.log(trade_type);
      this.logNo = logNo;
      this.modelId = id;
      this.exam_remark = exam_remark;
      this.isDetail = isDetail;
      this.status = status;
      this.trade_type = trade_type ? trade_type : "";
      console.log(this.trade_type);
      this.showModel = true;
    },
    async timeReturned(e) {
      if (e.startTime !== "") {
        this.parmValue.start = e.startTime;
      } else {
        this.parmValue.start = "";
      }
      if (e.endTime !== "") {
        this.parmValue.end = e.endTime;
      } else {
        this.parmValue.end = "";
      }
      if (this.parmValue.start !== "" && this.parmValue.end !== "") {
        this.parmValue.page = 1;
        await this.searchList();
      }
    },
    numReturned(e, type) {
      if (type === 0) {
        this.parmValue.total_low = e.lower; //最小金额
        this.parmValue.total_up = e.online; //最大金额
      } else if (type === 1) {
        this.parmValue.pay_low = e.lower; //最小金额
        this.parmValue.pay_up = e.online; //最大金额
      } else {
        this.parmValue.inv_low = e.lower; //最小金额
        this.parmValue.inv_up = e.online; //最大金额
      }
    },
    /**
     * 取消资金认领
     * @param {String} id id
     */
    async changeStatus(id) {
      await this.$confirm(`确定要取消认领申请？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            traNo: id,
          };
          const res = await asyncRequest.delete(model);
          if (res && res.code === 0) {
            this.$notify.success({
              title: "取消认领申请成功！",
              message: "",
            });
            this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },

    // 刷新表格
    async searchList() {
      if (
        (this.parmValue.total_low !== "" && this.parmValue.total_up === "") ||
        (this.parmValue.total_low === "" && this.parmValue.total_up !== "")
      ) {
        this.$message.warning("资金总额区间有误！");
        return;
      }
      if (this.select === "1") {
        this.parmValue.logNo = this.input;
        this.parmValue.name = "";
      } else {
        this.parmValue.logNo = "";
        this.parmValue.name = this.input;
      }
      this.parmValue.companyNo = this.code.join(",");
      this.loading = true;
      const res = await asyncRequest.list(this.parmValue);
      if (res && res.code === 0 && res.data) {
        this.tableData = [];
        let list = res.data.list;
        list.forEach((v1) => {
          let item = {
            children: [],
          };
          if (v1.trade && v1.trade.length === 1 && v1.is_all === "1") {
            item = Object.assign(item, v1.trade[0]);
            this.setType(item.status);
            item.statusName = this.sname;
            item.status_type = this.stype;
            item.amount = item.total_fee;
            item.trade_account = v1.trade_account;
            item.trade_out = v1.trade_out;
            item.trade_used = v1.trade_used;
            item.trade_type = v1.trade_type;
          } else if (
            (v1.trade && v1.trade.length > 1) ||
            (v1.trade && v1.trade.length === 1 && v1.is_all !== "1")
          ) {
            item = Object.assign(item, v1);
            item.status = item.is_all === "1" ? "5" : "6";
            this.setType(item.status);
            item.statusName = this.sname;
            item.traNo = item.logNo;
            item.status_type = this.stype;
            v1.trade.forEach((v2) => {
              this.setType(v2.status);
              v2.statusName = this.sname;
              v2.status_type = this.stype;
              v2.amount = v2.total_fee;
              v2.trade_account = v1.trade_account;
              v2.trade_out = v1.trade_out;
              v2.trade_used = v1.trade_used;
              v2.trade_type = v1.trade_type;
              let child = Object.assign({}, v2);
              item.children.push(child);
            });
          } else {
            item = v1;
            item.traNo = item.logNo;
            this.setType(item.status);
            item.statusName = this.sname;
            item.status_type = this.stype;
          }
          // console.log(item);
          this.tableData.push(item);
        });
        console.log(this.tableData);
        this.count = Number(res.data.count);
        // this.pageInfo.total = Number(res.data.count);
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.count = 0;
      }
      this.loading = false;
    },
    setType(status) {
      this.sname, (this.stype = "");
      switch (status) {
        case "1":
          this.sname = "未认领";
          this.stype = "warning";
          break;
        case "2":
          this.sname = "待审核";
          this.stype = "";
          break;
        case "3":
          this.sname = "认领成功";
          this.stype = "success";
          break;
        case "4":
          this.sname = "审核驳回";
          this.stype = "danger";
          break;
        case "5":
          this.sname = "全部认领";
          this.stype = "success";
          break;
        case "6":
          this.sname = "部分认领";
          this.stype = "warning";
          break;
        default:
          this.sname = "";
          this.stype = "";
          break;
      }
    },
    async remoteMethod(query) {
      this.selectLoading = true;
      if (query !== "") {
        this.activeOptions = [];
        const res = await asyncRequest.clist({
          page: 1,
          size: 100,
          company: query,
        });
        if (res && res.code === 0 && res.data && res.data.list) {
          this.activeOptions = res.data.list;
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      } else {
        this.activeOptions = [];
      }
      this.selectLoading = false;
    },

    async dlTemplate() {
      if (!this.downLoading) {
        this.downLoading = true;
        let elemIF = document.createElement("iframe");
        elemIF.src =
          this.fileUrl + "?time=" + timestampToTime(new Date().valueOf());
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
        this.$message.success(`资金模板下载成功！`);
        setTimeout(() => {
          this.downLoading = false;
        }, 500);
      }
    },
  },
};
</script>

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