<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-item" style="width: 120px;">
        <sys-origin-permission-select
          v-model="listQuery.sysOrigin"
          @change="changeSysOrigin"
          @onLoad="onLoadPermissionSysOrigin"
        />
      </div>

      <div class="filter-item" style="width: 120px;">
        <select-system-region
          ref="regionSelectPolicy"
          v-model="listQuery.region"
          :sys-origin="listQuery.sysOrigin"
          clearable
          placeholder="区域"
          @change="handleSearch"
        />
      </div>

      <el-select
        v-model="listQuery.status"
        placeholder="账单状态"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in teamBillStatus"
          :key="index"
          :dis="item.value === 'UNPAID'"
          :label="item.name"
          :value="item.value"
        />
      </el-select>

      <!-- <el-select
        v-model="listQuery.settleType"
        placeholder="结算状态"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in teamBillSettleTypes"
          :key="index"
          :label="item.name"
          :value="item.value"
        />
      </el-select> -->

      <div class="filter-item">
        <account-input
          v-model="listQuery.ownUserId"
          :sys-origin="listQuery.sysOrigin"
          placeholder="代理ID"
        />
      </div>

      <div class="filter-item">
        <el-input v-model="listQuery.id" placeholder="账单ID" />
      </div>

      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          style="width: 100%;"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期开始"
          end-placeholder="结束日期结束"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        :loading="importLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="clickExcel"
      >
        导出
      </el-button>
    </div>

    <el-table
      ref="teamTable"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column type="index" width="50" label="No" />
      <el-table-column
        label="代理"
        align="left"
        show-overflow-tooltip
        min-width="220"
      >
        <template slot-scope="scope">
          <user-table-exhibit
            :user-profile="scope.row.ownUserProfile"
            :query-details="true"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="区域"
        align="left"
        prop="regionName"
        show-overflow-tooltip
        min-width="100"
      />
      <el-table-column
        label="归属"
        prop="billBelong"
        align="center"
        show-overflow-tooltip
        min-width="80"
      />
      <!-- <el-table-column label="状态" align="left" show-overflow-tooltip min-width="80">
        <template slot-scope="scope">
          <div>{{ teamBillStatusMap[scope.row.status].name }}</div>
        </template>
      </el-table-column> -->

      <el-table-column
        v-if="
          listQuery.status === 'SETTLED' && listQuery.status !== 'PRE_CREATION'
        "
        label="工资"
        align="left"
        show-overflow-tooltip
        min-width="220"
      >
        <template slot-scope="scope">
          <div class="settled-row">
            <div class="col ">
              成员/代理: {{ scope.row.settleResult.memberSalary }}/{{
                scope.row.settleResult.ownSalary
              }}
            </div>
            <div class="col">
              合计: {{ scope.row.settleResult.totalSalary }}
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column align="left" show-overflow-tooltip>
        <template slot-scope="scope">
          <div class="flex-b">
            <div v-if="scope.row.settleType === 'GOLD' || scope.row.settleType === 'MONEY_GOLD'" class="settled-row">
              <div class="col">
                金币: {{ scope.row.settleResult.goldQuantity }}
              </div>
              <div v-if="scope.row.settleType === 'MONEY_GOLD'" class="col">
                工资: {{ scope.row.settleResult.salaryQuantity }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column> -->

      <!-- <el-table-column
        align="center"
        label="备注"
        show-overflow-tooltip
        min-width="60"
      >
        <template slot-scope="scope">
          <div class="settled-row settled-row-min">
            <el-link @click.native="clickInternalRemarks(scope.row)">{{
              scope.row.internalRemarks ? scope.row.internalRemarks.length : 0
            }}</el-link>
          </div>
        </template>
      </el-table-column> -->

      <el-table-column
        label="修改人"
        prop="updateUserNickname"
        align="center"
        show-overflow-tooltip
        min-width="80"
      />

      <el-table-column
        label="时间"
        align="center"
        show-overflow-tooltip
        min-width="200"
      >
        <template slot-scope="scope">
          <div>创建: {{ scope.row.createTime | dateFormat }}</div>
          <div>修改: {{ scope.row.updateTime | dateFormat }}</div>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="el-icon-more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="clickQueryDetails(scope.row)"
                >详情</el-dropdown-item
              >
              <!-- <el-dropdown-item
                :disabled="scope.row.status === 'PRE_CREATION'"
                @click.native="clickInternalRemarks(scope.row)"
                >内部备注</el-dropdown-item
              > -->
              <!-- <el-dropdown-item :disabled="scope.row.status === 'PRE_CREATION'" @click.native="clickRemarks(scope.row)">对外备注</el-dropdown-item> -->
              <!-- <el-dropdown-item v-if="settleBillStatus.includes(scope.row.status)" :disabled="scope.row.status === 'PRE_CREATION'" @click.native="clickSettle(scope.row)">结算账单</el-dropdown-item>
              <el-dropdown-item v-if="closeBillStatus.includes(scope.row.status)" :disabled="scope.row.status === 'PRE_CREATION'" @click.native="clickStatusChange(scope.row, 'CLOSE')">关闭订单</el-dropdown-item>
              <el-dropdown-item v-if="hangUpBillStatus.includes(scope.row.status)" :disabled="scope.row.status === 'PRE_CREATION'" @click.native="clickStatusChange(scope.row, 'HANG_UP')">挂起订单</el-dropdown-item> -->
              <!-- <el-dropdown-item :disabled="scope.row.status === 'PRE_CREATION'" @click.native="clickBillShare(scope.row)">分享账单-未实现</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="listQuery.lastId" class="load-more">
      <span v-if="notData">已加载全部</span>
      <el-button
        v-else
        size="mini"
        :disabled="loadMoreLoading"
        :loading="loadMoreLoading"
        @click="clickLoadMore"
        >加载更多</el-button
      >
    </div>

    <el-drawer
      title="导出条件"
      :visible="dialogExcelVisible"
      :before-close="exportConditionClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div class="exprot-select">
        <div class="drawer-form">
          <el-form
            ref="exportQuery"
            :rules="exportQueryRules"
            :model="excelQuery"
            label-position="left"
            label-width="70px"
          >
            <el-form-item label="区域" prop="region">
              <select-system-region
                v-model="excelQuery.region"
                :sys-origin="excelQuery.sysOrigin"
                placeholder="区域"
              />
            </el-form-item>

            <el-form-item label="状态" prop="billStatusList">
              <el-select
                v-model="excelQuery.billStatusList"
                multiple
                placeholder="账单状态"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in teamBillStatus"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="时间" prop="monthDate">
              <el-date-picker
                v-model="excelQuery.monthDate"
                value-format="yyyyMM"
                type="month"
                placeholder="选择月"
                style="width: 100%;"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button :disabled="importLoading" @click="exportConditionClose"
            >取 消</el-button
          >
          <el-button
            type="primary"
            :loading="importLoading"
            :disabled="importLoading"
            @click="handleExcel()"
            >确 定</el-button
          >
        </div>
      </div>
    </el-drawer>

    <details-drawer
      v-if="billDetailsVisible"
      :row="thatRow"
      @close="billDetailsVisible = false"
    />

    <team-bill-internal-remark
      v-if="teamBillInternalRemarkVisible"
      :row="thatRow"
      @close="teamBillInternalRemarkVisible = false"
      @addRemarks="addRemarks"
      @revemoRemarks="revemoRemarks"
    />

    <team-bill-remark
      v-if="teamBillRemarkVisible"
      :row="thatRow"
      @close="teamBillRemarkVisible = false"
      @success="teamBillRemarkSuccess"
    />

    <team-bill-settle
      v-if="teamBillSettleVisible"
      :row="thatRow"
      @close="teamBillSettleVisible = false"
      @success="teamBillSettleSUccess"
    />

    <team-bill-status
      v-if="teamBillStatusVisible"
      :status="teamBillChangeStatus"
      :bill-id="thatRow.id"
      @close="teamBillStatusVisible = false"
      @success="teamBillStatusSuccess"
    />

    <team-details-drawer
      v-if="teamDetailsDrawerVisible"
      :team-id="thatRow.teamProfile.id"
      @close="teamDetailsDrawerVisible = false"
    />
  </div>
</template>

<script>
import { listTeamBillTable, excelAnchorBill } from "@/api/team";
import { pickerOptions } from "@/constant/el-const";
import {
  billCyclePolicyTypes,
  teamBillStatus,
  teamBillStatusMap
} from "@/constant/team-type";

import TeamBillRemark from "./team-bill-remark";
import DetailsDrawer from "./details-drawer";
import TeamBillInternalRemark from "./team-bill-internal-remark";
import TeamBillSettle from "./team-bill-settle";
import TeamBillStatus from "./team-bill-status";
import TeamDetailsDrawer from "./../components/TeamDetailsDrawer";

export default {
  components: {
    TeamDetailsDrawer,
    DetailsDrawer,
    TeamBillInternalRemark,
    TeamBillRemark,
    TeamBillSettle,
    TeamBillStatus
  },
  data() {
    const commonRules = [
      { required: true, message: "必填字段不可为空", trigger: "blur" }
    ];
    return {
      importLoading: false,
      teamDetailsDrawerVisible: false,
      teamBillChangeStatus: "",
      teamBillStatusVisible: false,
      closeBillStatus: ["PAY_OUT", "HANG_UP"],
      hangUpBillStatus: ["PAY_OUT", "CLOSE"],
      settleBillStatus: ["PAY_OUT", "HANG_UP"],
      teamBillSettleVisible: false,
      teamBillRemarkVisible: false,
      teamBillInternalRemarkVisible: false,
      billDetailsVisible: false,
      teamBillStatusMap: teamBillStatusMap(),
      teamBillStatus,
      dialogExcelVisible: false,
      billCyclePolicyTypes,
      thatRow: {},
      pickerOptions,
      listQuery: {
        id: "",
        sysOrigin: "",
        teamId: "",
        status: "",
        settleType: "",
        region: "",
        startTime: "",
        endTime: "",
        lastId: "",
        limit: ""
      },
      excelQuery: {
        sysOrigin: "",
        billStatusStr: "",
        billStatusList: [],
        region: "",
        monthDate: ""
      },
      exportQueryRules: {
        billStatusList: commonRules,
        region: commonRules,
        monthDate: commonRules
      },
      listLoading: false,
      list: [],
      notData: false,
      loadMoreLoading: false,
      rangeDate: ""
    };
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0];
          this.listQuery.endTime = newVal[1];
          return;
        }
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    }
  },
  created() {
    this.listQuery.status = teamBillStatus[0].value;
  },
  methods: {
    renderData(isReset, loadMore = false) {
      const that = this;
      if (!that.listQuery.sysOrigin) {
        return;
      }
      if (isReset === true) {
        that.list = [];
        that.notData = false;
        that.listQuery.lastId = "";
      }
      that.loadMoreLoading = loadMore;
      that.listLoading = !loadMore;
      listTeamBillTable(that.listQuery)
        .then(res => {
          that.listLoading = false;
          that.loadMoreLoading = false;
          const { body } = res;
          const list = body || [];
          that.notData = list.length <= 0;
          if (!that.notData) {
            that.list = that.list.concat(list);
            that.listQuery.lastId = that.list[that.list.length - 1].id;
          }
        })
        .catch(er => {
          that.listLoading = false;
          that.loadMoreLoading = false;
        });
    },
    handleSearch() {
      this.renderData(true);
    },
    clickLoadMore() {
      const that = this;
      that.loadMoreLoading = true;
      that.renderData(false, true);
    },
    editTeamProfile(row) {
      this.thatRow = row;
      this.teamEditVisible = true;
    },
    tableSelectable(row) {
      return row.role !== "OWN";
    },
    changeSysOrigin(val) {
      this.handleSearch();
      // this.$refs.regionSelectPolicy.clearValue()
      // this.listQuery.region = ''
    },
    onLoadPermissionSysOrigin(val) {
      const that = this;
      that.renderData();
    },
    clickQueryDetails(row) {
      this.thatRow = row;
      this.billDetailsVisible = true;
    },
    clickInternalRemarks(row) {
      this.thatRow = row;
      this.teamBillInternalRemarkVisible = true;
    },
    addRemarks(remarks) {
      this.thatRow.internalRemarks.push(remarks);
    },
    revemoRemarks(index) {
      this.thatRow.internalRemarks.splice(index, 1);
    },
    clickRemarks(row) {
      this.thatRow = row;
      this.teamBillRemarkVisible = true;
    },
    teamBillRemarkSuccess(res) {
      const that = this;
      that.$opsMessage.success();
      if (res) {
        that.thatRow.remarks = res.remarks;
        that.teamBillRemarkVisible = false;
      }
    },
    clickSettle(row) {
      const that = this;
      that.thatRow = row;
      that.teamBillSettleVisible = true;
    },
    clickStatusChange(row, status) {
      const that = this;
      that.thatRow = row;
      that.teamBillStatusVisible = true;
      that.teamBillChangeStatus = status;
    },
    teamBillStatusSuccess(form) {
      this.teamBillStatusVisible = false;
      this.thatRow.status = form.status;
    },
    clickBillShare(row) {
      this.$opsMessage.fail("还没有实现");
    },
    clickQueryTeamDetails(row) {
      this.thatRow = row;
      this.teamDetailsDrawerVisible = true;
    },
    teamBillSettleSUccess(form) {
      this.list = this.list.filter(item => form.id !== item.id);
      this.teamBillSettleVisible = false;
      this.$opsMessage.success();
    },
    clickExcel() {
      this.excelQuery.sysOrigin = this.listQuery.sysOrigin;
      this.dialogExcelVisible = true;
    },
    exportConditionClose() {
      if (this.importLoading) {
        this.$opsMessage.warn("正在执行导出, 请稍等~");
        return;
      }
      this.dialogExcelVisible = false;
    },
    handleExcel() {
      const that = this;
      that.excelQuery.billStatusStr = that.excelQuery.billStatusList.join(",");

      that.$refs.exportQuery.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return false;
        }
        that.importLoading = true;
        excelAnchorBill(that.excelQuery, "AnchorWorkDetails")
          .then(res => {
            that.importLoading = false;
            this.dialogExcelVisible = false;
          })
          .catch(er => {
            that.importLoading = false;
            this.dialogExcelVisible = false;
            this.$opsMessage.fail("下载失败！");
          });
      });
    }
  }
};
</script>
<style scoped lang="scss">
.load-more {
  text-align: center;
  padding: 10px;
}
</style>
