<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        :placeholder="$t('pages.userFreight.filter.system')"
        style="width: 120px"
        class="filter-item filter-item--system"
        @change="handleSearch"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;">
            <sys-origin-icon :icon="item.value" :desc="item.value"
          /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>

      <el-select
        v-model="listQuery.h5Display"
        :placeholder="$t('pages.userFreight.filter.displayStatus')"
        style="width: 120px"
        class="filter-item filter-item--display"
        clearable
        @change="handleSearch"
      >
        <el-option :label="$t('pages.userFreight.option.show')" :value="true" />
        <el-option :label="$t('pages.userFreight.option.hide')" :value="false" />
      </el-select>
      <el-select
        v-model="listQuery.dealer"
        :placeholder="$t('pages.userFreight.filter.isDealer')"
        style="width: 120px"
        class="filter-item filter-item--dealer"
        clearable
        @change="handleSearch"
      >
        <el-option :label="$t('pages.userFreight.option.no')" :value="false" />
        <el-option :label="$t('pages.userFreight.option.yes')" :value="true" />
      </el-select>

      <el-select
        v-model="listQuery.close"
        :placeholder="$t('pages.userFreight.filter.status')"
        style="width: 120px"
        class="filter-item filter-item--status"
        clearable
        @change="handleSearch"
      >
        <el-option :label="$t('pages.userFreight.option.normal')" :value="false" />
        <el-option :label="$t('pages.userFreight.option.closed')" :value="true" />
      </el-select>
      <!-- <el-input
        v-model.trim="listQuery.id"
        v-number
        placeholder="ID"
        style="width: 200px;"
        class="filter-item"
      /> -->
      <div class="filter-item filter-item--user">
        <account-input
          v-model="listQuery.userId"
          :sys-origin="listQuery.sysOrigin"
          :placeholder="$t('pages.userFreight.filter.userId')"
        />
      </div>
      <el-button
        class="filter-item filter-item--search"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        {{ $t('pages.userFreight.action.search') }}
      </el-button>
      <el-button
        class="filter-item filter-item--create"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('pages.userFreight.action.add') }}
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >
      <el-table-column :label="$t('pages.userFreight.table.system')" prop="sysOrigin" align="center" width="80">
        <template slot-scope="scope">
          <sys-origin-icon
            :icon="scope.row.sysOrigin"
            :desc="scope.row.sysOrigin"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.userFreight.table.user')" align="center" min-width="200">
        <template slot-scope="scope">
          <user-table-exhibit
            :user-profile="scope.row.userBaseInfo"
            :query-details="true"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="earnPoints"
        :label="$t('pages.userFreight.table.totalEarned')"
        align="center"
        min-width="100"
      />
      <el-table-column
        prop="consumptionPoints"
        :label="$t('pages.userFreight.table.totalShipped')"
        align="center"
        min-width="100"
      />
      <el-table-column
        prop="balance"
        :label="$t('pages.userFreight.table.balance')"
        align="center"
        min-width="100"
      />
      <el-table-column width="200" :label="$t('pages.userFreight.table.display')" align="center" min-width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.h5Display"
            :active-value="true"
            :inactive-value="false"
            :disabled="scope.row.close"
            @change="showSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column width="200" :label="$t('pages.userFreight.table.normal')" align="center" min-width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.close"
            :active-value="false"
            :inactive-value="true"
            @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        width="200"
        :label="$t('pages.userFreight.table.dealer')"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.dealer"
            :active-value="true"
            :inactive-value="false"
            @change="switchChangeDealer(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        width="200"
        :label="$t('pages.userFreight.table.superDealer')"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.superDealer"
            :active-value="true"
            :inactive-value="false"
            @change="switchChangeSuperDealer(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="sellerQuantity"
        width="200"
        :label="$t('pages.userFreight.table.authorizedSellerQuantity')"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="showSellerInfo(scope.row)">
            {{ scope.row.sellerQuantity }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="realSellerQuantity"
        width="200"
        :label="$t('pages.userFreight.table.actualAuthorizedSellerQuantity')"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.realSellerQuantity }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        :label="$t('pages.userFreight.table.createdAt')"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        :label="$t('pages.userFreight.table.updatedAt')"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('pages.userFreight.table.actions')" align="center" width="190">
        <template slot-scope="scope">
          <el-button type="text" @click.native="handleUpdate(scope.row)"
            >{{ $t('pages.userFreight.action.edit') }}</el-button
          >
          <el-button type="text" @click="showGoldInputBox(scope.row, true)"
            >{{ $t('pages.userFreight.action.ship') }}</el-button
          >
          <el-button type="text" @click="showGoldInputBox(scope.row, false)"
            >{{ $t('pages.userFreight.action.deduct') }}</el-button
          >
          <el-button type="text" @click="runningWaterVisible = true"
            >{{ $t('pages.userFreight.action.runningWater') }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <form-edit
      v-if="formEditVisable"
      :row="thatRow"
      :sys-origin="listQuery.sysOrigin"
      @close="formEditClose"
      @success="formEditSuccess"
    />

    <running-water
      v-if="runningWaterVisible"
      :row="thatRow"
      @close="runningWaterVisible = false"
    />

    <seller-info
      v-if="showSellerInfoVisable"
      :row="sellerInfoEditParam"
      @close="sellerInfoClose"
    />

    <div class="gold-input-box">
      <el-dialog
        :title="type ? $t('pages.userFreight.dialog.ship') : $t('pages.userFreight.dialog.deduct')"
        :visible.sync="goldInputBoxVisible"
        width="400px"
      >
        <el-form
          ref="form"
          :rules="formRules"
          :model="formData"
          label-position="left"
          label-width="80px"
          style="width: 300px; margin-left:50px;"
        >
          <el-form-item :label="$t('pages.userFreight.form.gold')" prop="earnPoints">
            <el-input
              v-model.trim="formData.earnPoints"
              :placeholder="type ? $t('pages.userFreight.placeholder.shipGoldQuantity') : $t('pages.userFreight.placeholder.deductGoldQuantity')"
            />
          </el-form-item>
          <el-form-item v-if="type == true" :label="$t('pages.userFreight.form.amount')" prop="amount">
            <el-input v-model.trim="formData.amount" :placeholder="$t('pages.userFreight.placeholder.amount')" />
          </el-form-item>
          <el-form-item
            v-if="type == true"
            :label="$t('pages.userFreight.form.rechargeType')"
            prop="rechargeType"
          >
            <el-select
              v-model.trim="formData.rechargeType"
              :placeholder="$t('pages.userFreight.placeholder.rechargeType')"
              clearable
              style="width:100%;"
              class="filter-item"
            >
              <el-option :label="$t('pages.userFreight.rechargeType.clipsPayPurchase')" :value="'CLIPSPAY-进货'" />
              <el-option :label="$t('pages.userFreight.rechargeType.payoneerPurchase')" :value="'Payoneer-进货'" />
              <el-option :label="$t('pages.userFreight.rechargeType.paypalPurchase')" :value="'Paypal-进货'" />
              <el-option :label="$t('pages.userFreight.rechargeType.salaryPurchase')" :value="'工资-进货'" />
              <el-option :label="$t('pages.userFreight.rechargeType.bankCardExchange')" :value="'银行卡兑换'" />
              <el-option :label="$t('pages.userFreight.rechargeType.usdtPurchase')" :value="'USDT-进货'" />
              <el-option :label="$t('pages.userFreight.rechargeType.goldCompensation')" :value="'金币补偿'" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.userFreight.form.remark')" prop="remark">
            <el-input v-model.trim="formData.remark" :placeholder="$t('pages.userFreight.placeholder.remark')" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="hideDialog()">
            {{ $t('pages.userFreight.action.cancel') }}
          </el-button>
          <el-button
            v-loading="listLoading"
            type="primary"
            @click="goldSubmit()"
          >
            {{ $t('pages.userFreight.action.submit') }}
          </el-button>
        </div>
      </el-dialog>
      <el-dialog :title="$t('pages.userFreight.dialog.edit')" :visible.sync="updateBoxVisible" width="400px">
        <el-form
          ref="form"
          :rules="formRules"
          :model="infoData"
          label-position="left"
          label-width="80px"
          style="width: 300px; margin-left:50px;"
        >
          <el-form-item :label="$t('pages.userFreight.form.contactInfo')" prop="contactInfo">
            <el-input
              v-model.trim="infoData.contactInfo"
              :placeholder="$t('pages.userFreight.placeholder.contactInfo')"
            />
          </el-form-item>
          <el-form-item :label="$t('pages.userFreight.form.supportedCountries')" prop="contactInfo">
            <el-input
              v-model.trim="infoData.supportedCountries"
              :placeholder="$t('pages.userFreight.placeholder.supportedCountries')"
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="hideDialog()">
            {{ $t('pages.userFreight.action.cancel') }}
          </el-button>
          <el-button
            v-loading="updateLoading"
            type="primary"
            @click="updateInfo()"
          >
            {{ $t('pages.userFreight.action.save') }}
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  pageFreight,
  shipFreight,
  deductionFreight,
  switchStatusFreight,
  showStatusFreight,
  switchStatusDealer,
  switchStatusSuperDealer,
  updateInfoCP // 更新货运代理账户信息（支持的国家和联系方式）
} from "@/api/app-user";
import Pagination from "@/components/Pagination";
import FormEdit from "./form-edit";
import RunningWater from "./running-water";
import SellerInfo from "./seller-info";
import { mapGetters } from "vuex";

export default {
  name: "UserPropsTable",
  components: { Pagination, FormEdit, RunningWater, SellerInfo },
  data() {
    const commonRules = [
      { required: true, message: this.$t("pages.userFreight.validation.required"), trigger: "blur" }
    ];

    return {
      runningWaterVisible: false,
      showSellerInfoVisable: false,
      sellerInfoEditParam: {},
      thatRow: null,
      userInfo: {},
      searchDisabled: false,
      updateBoxVisible: false,
      goldInputBoxVisible: false,
      // true：发货  false：扣除
      type: false,
      thatSelectedUserId: "",
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        close: false,
        dealer: "",
        startTime: "",
        endTime: ""
      },
      formData: {
        userId: "",
        earnPoints: "",
        sysOrigin: "",
        amount: "",
        rechargeType: "",
        remark: ""
      },
      listLoading: true,
      formEditVisable: false,

      // 支持的国家和联系方式
      infoData: {
        id: 0, //代理id
        supportedCountries: "", //支持的国家
        contactInfo: "" //联系方式
      },
      updateLoading: false, //更新提交加载中
      formRules: {
        userId: commonRules,
        earnPoints: {
          required: true,
          message: this.$t("pages.userFreight.validation.requiredNotEmpty"),
          trigger: "blur"
        },
        amount: commonRules,
        rechargeType: commonRules,
        sysOrigin: commonRules,
        supportedCountries: commonRules,
        contactInfo: commonRules
      }
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"])
  },
  created() {
    const that = this;
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    that.listQuery.sysOrigin = querySystem.value;
    that.renderData();
  },
  methods: {
    handleImageUrl(row) {
      return row.propsCover ? row.propsCover : "";
    },
    renderData(isReset) {
      const that = this;
      if (isReset === true) {
        that.listQuery.cursor = 1;
      }
      that.listLoading = true;
      pageFreight(that.listQuery)
        .then(res => {
          const { body } = res;
          that.total = body.total || 0;
          that.list = body.records;
          that.listLoading = false;
        })
        .catch(er => {
          that.listLoading = false;
        });
    },
    handleSearch() {
      this.renderData(true);
    },
    handleCreate() {
      this.thatRow = null;
      this.formEditVisable = true;
    },
    handleClose() {
      this.$emit("close");
    },
    handleMouseEnter(row) {
      this.thatRow = row;
    },
    formEditClose() {
      this.formEditVisable = false;
    },
    formEditSuccess() {
      this.formEditVisable = false;
      this.renderData();
    },
    handleSwitchChange(row) {
      switchStatusFreight(row.id, row.close)
        .then(res => {})
        .catch(er => {
          row.close = !row.close;
        });
    },
    showSwitchChange(row) {
      showStatusFreight(row.id, row.h5Display)
        .then(res => {})
        .catch(er => {
          row.h5Display = !row.h5Display;
        });
    },
    switchChangeDealer(row) {
      switchStatusDealer(row.id, row.dealer)
        .then(res => {})
        .catch(er => {
          row.dealer = !row.dealer;
        });
    },
    switchChangeSuperDealer(row) {
      switchStatusSuperDealer(row.id, row.superDealer)
        .then(res => {})
        .catch(er => {
          row.superDealer = !row.superDealer;
        });
    },

    showSellerInfo(row) {
      const that = this;
      console.log("---->");
      that.showSellerInfoVisable = true;
      this.sellerInfoEditParam = row;
    },
    sellerInfoClose() {
      this.showSellerInfoVisable = false;
      this.renderData();
    },
    showGoldInputBox(row, type) {
      const that = this;
      that.type = type;

      that.formData = {
        userId: row.userId,
        earnPoints: "",
        sysOrigin: row.sysOrigin,
        remark: ""
      };
      that.goldInputBoxVisible = true;
    },

    // 打开修改弹窗
    handleUpdate(row) {
      const that = this;

      that.infoData = {
        id: row.id,
        supportedCountries: row.supportedCountries || "",
        contactInfo: row.contactInfo || ""
      };
      console.log("infoData:", that.infoData);

      that.updateBoxVisible = true;
    },

    // 关闭弹窗（通用）
    hideDialog() {
      const that = this;
      that.goldInputBoxVisible = false;
      that.updateBoxVisible = false;
    },

    // 提交发货/扣款
    goldSubmit() {
      const that = this;

      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return;
        }
        that.listLoading = true;
        if (that.type) {
          shipFreight(that.formData)
            .then(res => {
              that.$opsMessage.success();
              that.goldInputBoxVisible = false;
              that.listLoading = false;
              that.renderData();
            })
            .catch(er => {
              that.listLoading = false;
              that.$opsMessage.success();
              console.error(er);
            });
          return;
        }

        deductionFreight(that.formData)
          .then(res => {
            that.$opsMessage.success();
            that.goldInputBoxVisible = false;
            that.listLoading = false;
            that.renderData();
          })
          .catch(er => {
            that.listLoading = false;
            that.$opsMessage.success();
            console.error(er);
          });
      });
    },

    // 提交更新信息(支持国家和联系方式)
    updateInfo() {
      const that = this;

      that.updateLoading = true; //加载中
      updateInfoCP(that.infoData)
        .then(res => {
          that.handleSearch(); //重新加载数据
          that.infoData = {
            id: 0, //代理id
            supportedCountries: "", //支持的国家
            contactInfo: "" //联系方式
          };
          that.updateLoading = false; //加载完毕
          that.hideDialog(); //隐藏弹窗
        })
        .catch(er => {
          that.infoData = {
            id: 0, //代理id
            supportedCountries: "", //支持的国家
            contactInfo: "" //联系方式
          };
          that.updateLoading = false; //加载完毕
          that.hideDialog(); //隐藏弹窗
        });
    }
  }
};
</script>

<style scoped lang="scss">
.filter-item--system {
  order: 10;
}

.filter-item--user {
  order: 20;
}

.filter-item--status {
  order: 30;
}

.filter-item--display {
  order: 40;
}

.filter-item--dealer {
  order: 50;
}

.filter-item--search {
  order: 60;
}

.filter-item--create {
  order: 70;
}
</style>
