<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="$t('pages.teamBill.placeholder.region')"
          @change="handleSearch"
        />
      </div>

      <el-select
        v-model="listQuery.status"
        :placeholder="$t('pages.teamBill.placeholder.billStatus')"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in teamBillStatus"
          :key="index"
          :dis="item.value === 'UNPAID'"
          :label="teamBillStatusName(item.value)"
          :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="$t('pages.teamBill.placeholder.agentId')"
        />
      </div>

      <div class="filter-item">
        <el-input v-model="listQuery.id" :placeholder="$t('pages.teamBill.placeholder.billId')" />
      </div>

      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          style="width: 100%;"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          :range-separator="$t('pages.teamBill.date.rangeSeparator')"
          :start-placeholder="$t('pages.teamBill.date.start')"
          :end-placeholder="$t('pages.teamBill.date.end')"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        {{ $t('pages.teamBill.action.search') }}
      </el-button>
      <el-button
        :loading="importLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="clickExcel"
      >
        {{ $t('pages.teamBill.action.export') }}
      </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="$t('pages.teamBill.table.agent')"
        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="$t('pages.teamBill.table.region')"
        align="left"
        prop="regionName"
        show-overflow-tooltip
        min-width="100"
      />
      <el-table-column
        :label="$t('pages.teamBill.table.belong')"
        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="$t('pages.teamBill.table.salary')"
        align="left"
        show-overflow-tooltip
        min-width="220"
      >
        <template slot-scope="scope">
          <div class="settled-row">
            <div class="col ">
              {{ $t('pages.teamBill.label.memberAgent') }}: {{ scope.row.settleResult.memberSalary }}/{{
                scope.row.settleResult.ownSalary
              }}
            </div>
            <div class="col">
              {{ $t('pages.teamBill.label.total') }}: {{ 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="$t('pages.teamBill.table.updatedBy')"
        prop="updateUserNickname"
        align="center"
        show-overflow-tooltip
        min-width="80"
      />

      <el-table-column
        :label="$t('pages.teamBill.table.time')"
        align="center"
        show-overflow-tooltip
        min-width="200"
      >
        <template slot-scope="scope">
          <div>{{ $t('pages.teamBill.label.created') }}: {{ scope.row.createTime | dateFormat }}</div>
          <div>{{ $t('pages.teamBill.label.updated') }}: {{ scope.row.updateTime | dateFormat }}</div>
        </template>
      </el-table-column>

      <el-table-column fixed="right" :label="$t('pages.teamBill.table.actions')" 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)"
                >{{ $t('pages.teamBill.action.details') }}</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">{{ $t('pages.teamBill.action.loadedAll') }}</span>
      <el-button
        v-else
        size="mini"
        :disabled="loadMoreLoading"
        :loading="loadMoreLoading"
        @click="clickLoadMore"
        >{{ $t('pages.teamBill.action.loadMore') }}</el-button
      >
    </div>

    <el-drawer
      :title="$t('pages.teamBill.exportDialog.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="$t('pages.teamBill.exportDialog.region')" prop="region">
              <select-system-region
                v-model="excelQuery.region"
                :sys-origin="excelQuery.sysOrigin"
                :placeholder="$t('pages.teamBill.placeholder.region')"
              />
            </el-form-item>

            <el-form-item :label="$t('pages.teamBill.exportDialog.status')" prop="billStatusList">
              <el-select
                v-model="excelQuery.billStatusList"
                multiple
                :placeholder="$t('pages.teamBill.placeholder.billStatus')"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in teamBillStatus"
                  :key="index"
                  :label="teamBillStatusName(item.value)"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('pages.teamBill.exportDialog.time')" prop="monthDate">
              <el-date-picker
                v-model="excelQuery.monthDate"
                value-format="yyyyMM"
                type="month"
                :placeholder="$t('pages.teamBill.placeholder.selectMonth')"
                style="width: 100%;"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button :disabled="importLoading" @click="exportConditionClose"
            >{{ $t('pages.teamBill.action.cancel') }}</el-button
          >
          <el-button
            type="primary"
            :loading="importLoading"
            :disabled="importLoading"
            @click="handleExcel()"
            >{{ $t('pages.teamBill.action.confirm') }}</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
} 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: this.$t("pages.teamBill.validation.requiredField"),
        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,
      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;
    },
    teamBillStatusName(status) {
      return this.$t(`pages.teamBill.status.${status}`);
    },
    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(this.$t("pages.teamBill.message.notImplemented"));
    },
    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(this.$t("pages.teamBill.message.exporting"));
        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(this.$t("pages.teamBill.message.downloadFailed"));
          });
      });
    }
  }
};
</script>
<style scoped lang="scss">
.load-more {
  text-align: center;
  padding: 10px;
}
</style>
