<template>
  <div class="app-container-region">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        :placeholder="$t('pages.regionConfig.filter.system')"
        style="width:120px;"
        class="filter-item"
        @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-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        {{ $t("common.search") }}
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t("pages.regionConfig.action.add") }}
      </el-button>
      <div class="filter-item" style="float: right;">
        <el-link
          href="https://img.sugartimeapp.com/web/country-code-and-language-code-data.xlsx"
          ><i class="el-icon-download" />{{
            $t("pages.regionConfig.filter.countryLanguageCodeDoc")
          }}</el-link
        >
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column
        prop="regionCode"
        :label="$t('pages.regionConfig.table.regionCode')"
        align="center"
      />
      <el-table-column
        prop="regionName"
        :label="$t('pages.regionConfig.table.regionName')"
        align="center"
      />
      <el-table-column
        :label="$t('pages.regionConfig.table.country')"
        align="center"
        prop="countryCodes"
        min-width="200"
      />
      <el-table-column
        :label="$t('pages.regionConfig.table.language')"
        align="center"
        prop="langeCodes"
        min-width="100"
      />
      <el-table-column
        prop="remarks"
        :label="$t('pages.regionConfig.table.remarks')"
        align="center"
      />
      <el-table-column
        prop="createTime"
        :label="$t('pages.regionConfig.table.createdAt')"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        :label="$t('pages.regionConfig.table.actions')"
        align="center"
        width="78"
      >
        <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="handleUpdate(scope.row)"
                >{{ $t("pages.regionConfig.action.edit") }}</el-dropdown-item
              >
              <el-dropdown-item @click.native="clickCopyRegionId(scope.row)"
                >{{ $t("pages.regionConfig.action.copyId") }}</el-dropdown-item
              >
              <el-dropdown-item @click.native="clickResetWithdrawal(scope.row)"
                >{{
                  $t("pages.regionConfig.action.resetWithdrawal")
                }}</el-dropdown-item
              >
              <!-- <el-dropdown-item @click.native="handleDelete(scope.row)">删除</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
      :title="drawerTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div v-loading="submitLoading">
        <div class="drawer-form">
          <el-form
            ref="form"
            class="i18n-form i18n-form--wide"
            :model="form"
            :rules="rules"
            label-width="150px"
          >
            <el-form-item
              :label="$t('pages.regionConfig.form.regionCode')"
              prop="regionCode"
            >
              <el-input
                v-model.trim="form.regionCode"
                :disabled="form.id !== ''"
                :placeholder="$t('pages.regionConfig.placeholder.regionCode')"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('pages.regionConfig.form.regionName')"
              prop="regionName"
            >
              <el-input
                v-model.trim="form.regionName"
                :placeholder="$t('pages.regionConfig.placeholder.regionName')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('pages.regionConfig.form.countryCodes')"
              prop="countryCodes"
            >
              <el-input
                v-model.trim="form.countryCodes"
                :placeholder="$t('pages.regionConfig.placeholder.countryCodes')"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('pages.regionConfig.form.languageCodes')"
              prop="langeCodes"
            >
              <el-input
                v-model.trim="form.langeCodes"
                :placeholder="$t('pages.regionConfig.placeholder.languageCodes')"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('pages.regionConfig.form.remarks')">
              <el-input
                v-model.trim="form.remarks"
                type="textarea"
                :placeholder="$t('pages.regionConfig.placeholder.remarks')"
                maxlength="200"
                rows="5"
                resize="none"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              prop="withdrawalWaysList"
              :label="$t('pages.regionConfig.form.withdrawalWays')"
            >
              <el-select
                v-model="form.withdrawalWaysList"
                multiple
                :placeholder="$t('pages.regionConfig.placeholder.select')"
                style="width:100%;"
              >
                <el-option
                  v-for="item in bankCardTypes"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('pages.regionConfig.form.usdWalletSettings')">
              <el-row
                v-for="(item, index) in form.metadatas"
                :key="index"
                :gutter="10"
              >
                <div v-if="item.key === 'openDailyAutoSalary'">
                  <el-divider />
                  <span>
                    <el-tooltip :content="$t(item.describeKey)">
                      <i class="el-icon-info" />
                    </el-tooltip>
                    {{ $t("pages.regionConfig.form.paymentSalaryMode") }}:
                  </span>
                  <el-radio
                    v-model="item.value"
                    :disabled="isOpenDailyAutoSalary"
                    :label="'false'"
                    >{{ $t("pages.regionConfig.word.monthlySettlement") }}</el-radio
                  >
                  <el-radio v-model="item.value" :label="'true'"
                    >{{ $t("pages.regionConfig.word.dailySettlement") }}</el-radio
                  >
                </div>
                <div v-else>
                  <el-checkbox
                    v-if="item.type === 'checkbox'"
                    v-model="item.value"
                    :disabled="item.key === 'hostSalaryToAgent'"
                  >
                    {{ $t(item.labelKey) }}
                  </el-checkbox>
                  <el-tooltip :content="$t(item.describeKey)">
                    <i class="el-icon-info" />
                  </el-tooltip>
                </div>
              </el-row>
            </el-form-item>

            <el-form-item
              :label="$t('pages.regionConfig.form.diamondWalletSettings')"
            >
              <div v-if="listQuery.sysOrigin === 'YOLO'" style="color: red;">
                {{ $t("pages.regionConfig.message.yoloWalletConfigShared") }}
              </div>
              <el-row
                v-for="(item, index) in form.diamondMetadatas"
                :key="index"
                :gutter="10"
              >
                <div v-if="item.key === 'openDailyAutoSalary'">
                  <!-- <el-divider />
                  <span>
                    <el-tooltip :content="item.describe">
                      <i class="el-icon-info" />
                    </el-tooltip>
                    支付工资模式:
                  </span>
                  <el-radio v-model="item.value" :disabled="isOpenDailyAutoSalary" :label="'false'">月结模式</el-radio>
                  <el-radio v-model="item.value" :label="'true'">日结模式</el-radio> -->
                </div>
                <div v-else>
                  <el-checkbox
                    v-if="item.type === 'checkbox'"
                    v-model="item.value"
                    :disabled="item.key === 'hostSalaryToAgent'"
                  >
                    {{ $t(item.labelKey) }}
                  </el-checkbox>
                  <el-tooltip :content="$t(item.describeKey)">
                    <i class="el-icon-info" />
                  </el-tooltip>
                </div>
              </el-row>
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button type="primary" @click="submitForm()">{{
            $t("pages.regionConfig.action.save")
          }}</el-button>
          <el-button @click="handleClose()">{{ $t("common.cancel") }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  regionConfigTable,
  updateRegionConfig,
  addRegionConfig,
  deleteRegionConfig,
  resetRegionWithdrawal
} from "@/api/sys";
import { mapGetters } from "vuex";
import { copyText } from "@/utils";
import { bankCardTypes } from "@/constant/type";

const METADATA_DEFINITIONS = {
  walletVisible: { type: "checkbox", defaultValue: false },
  agentWalletVisible: { type: "checkbox", defaultValue: false },
  hostSalaryToAgent: { type: "checkbox", defaultValue: false },
  openExchangeGold: { type: "checkbox", defaultValue: false },
  openTransfer: { type: "checkbox", defaultValue: false },
  openWithdraw: { type: "checkbox", defaultValue: false },
  openDiamondExchangeGold: { type: "checkbox", defaultValue: false },
  openTeamDelHost: { type: "checkbox", defaultValue: false },
  openHostApplyQuitTeam: { type: "checkbox", defaultValue: false },
  openBankCardMenu: { type: "checkbox", defaultValue: false },
  openKycMenu: { type: "checkbox", defaultValue: false },
  openDailyAutoSalary: { type: "radio", defaultValue: "false" }
};

function createMetadata(keys) {
  return keys.map(key => ({
    key,
    value: METADATA_DEFINITIONS[key].defaultValue,
    type: METADATA_DEFINITIONS[key].type,
    labelKey: `pages.regionConfig.metadata.${key}.label`,
    describeKey: `pages.regionConfig.metadata.${key}.describe`
  }));
}

function getFormData() {
  return {
    id: "",
    sysOrigin: "",
    regionCode: "",
    langeCodes: "",
    countryCodes: "",
    remarks: "",
    regionName: "",
    withdrawalWays: "",
    withdrawalWaysList: [],
    metadatas: createMetadata([
      "walletVisible",
      "agentWalletVisible",
      "hostSalaryToAgent",
      "openExchangeGold",
      "openTransfer",
      "openWithdraw",
      "openDiamondExchangeGold",
      "openTeamDelHost",
      "openHostApplyQuitTeam",
      "openBankCardMenu",
      "openKycMenu",
      "openDailyAutoSalary"
    ]),
    diamondMetadatas: createMetadata([
      "walletVisible",
      "agentWalletVisible",
      "hostSalaryToAgent",
      "openExchangeGold",
      "openTransfer",
      "openWithdraw",
      "openDailyAutoSalary"
    ]),
    metadata: {},
    diamondMetadata: {}
  };
}
export default {
  name: "RegionConfig",
  data() {
    return {
      list: [],
      bankCardTypes,
      listQuery: {
        sysOrigin: "ATYOU"
      },
      formVisible: false,
      isOpenDailyAutoSalary: false,
      textOptTitleKey: "",
      form: getFormData(),
      submitLoading: false,
      listLoading: true
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"]),
    drawerTitle() {
      if (!this.textOptTitleKey) {
        return "";
      }
      return this.$t("pages.regionConfig.dialog.title", {
        action: this.$t(this.textOptTitleKey),
        system: this.listQuery.sysOrigin
      });
    },
    rules() {
      return {
        sysOrigin: [
          {
            required: true,
            message: this.$t("pages.regionConfig.validation.requiredField"),
            trigger: "blur"
          }
        ],
        regionName: [
          {
            required: true,
            message: this.$t("pages.regionConfig.validation.requiredField"),
            trigger: "blur"
          }
        ],
        regionCode: [
          {
            required: true,
            message: this.$t("pages.regionConfig.validation.requiredField"),
            trigger: "blur"
          }
        ]
      };
    }
  },
  created() {
    this.renderData();
  },
  methods: {
    renderData() {
      const that = this;
      that.listLoading = true;
      regionConfigTable(that.listQuery).then(res => {
        const { body } = res;
        that.list = body;
        that.listLoading = false;
      });
    },
    handleSearch() {
      this.renderData();
    },
    submitForm() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true;
          that.form.sysOrigin = that.listQuery.sysOrigin;

          that.form.metadatas.forEach(item => {
            that.form.metadata[item.key] = item.value;
          });
          that.form.diamondMetadatas.forEach(item => {
            that.form.diamondMetadata[item.key] = item.value;
          });

          if (that.form.id) {
            updateRegionConfig(that.form)
              .then(res => {
                that.submitLoading = false;
                that.formVisible = false;
                that.form = getFormData();
                that.renderData();
              })
              .catch(er => {
                that.submitLoading = false;
                console.error(er);
                this.$emit("fail");
              });
            return;
          }
          addRegionConfig(that.form)
            .then(res => {
              that.submitLoading = false;
              that.formVisible = false;
              that.form = getFormData();
              that.renderData();
            })
            .catch(er => {
              that.submitLoading = false;
              console.error(er);
            });
        } else {
          console.error("error submit!!");
          return false;
        }
      });
    },
    handleClose() {
      this.formVisible = false;
    },
    handleCreate() {
      this.formVisible = true;
      this.textOptTitleKey = "pages.regionConfig.action.add";
      this.isOpenDailyAutoSalary = false;
      this.form = getFormData();
    },
    clickResetWithdrawal(row) {
      const that = this;
      that
        .$confirm(
          this.$t("pages.regionConfig.confirm.resetWithdrawal"),
          this.$t("pages.regionConfig.confirm.title"),
          {
            confirmButtonText: this.$t("pages.regionConfig.action.confirm"),
            cancelButtonText: this.$t("common.cancel"),
            type: "warning"
          }
        )
        .then(() => {
          resetRegionWithdrawal(row.id)
            .then(res => {
              that.$message({
                type: "success",
                message: that.$t("pages.regionConfig.message.resetSuccess")
              });
              that.renderData();
            })
            .catch(er => {
              // that.$opsMessage.success()
            });
        })
        .catch(() => {});
    },
    clickCopyRegionId(row) {
      copyText(row.id)
        .then(() => {
          this.$opsMessage.success();
        })
        .catch(er => {
          this.$opsMessage.fail();
        });
    },
    handleUpdate(row) {
      this.textOptTitleKey = "pages.regionConfig.action.edit";
      this.formVisible = true;

      this.isOpenDailyAutoSalary = false;

      const resForm = Object.assign({}, row);
      resForm.metadatas = getFormData().metadatas;
      if (!resForm.metadata) {
        resForm.metadata = {};
      }
      if (row.metadata) {
        resForm.metadatas.forEach(item => {
          if (item.type === "checkbox") {
            item.value = row.metadata[item.key] === "true";
          } else {
            item.value = row.metadata[item.key];
          }

          if (item.key === "openDailyAutoSalary" && item.value === "true") {
            this.isOpenDailyAutoSalary = true;
          }
        });
      }

      resForm.diamondMetadatas = getFormData().diamondMetadatas;
      if (!resForm.diamondMetadata) {
        resForm.diamondMetadata = {};
      }
      if (row.diamondMetadata) {
        resForm.diamondMetadatas.forEach(item => {
          if (item.type === "checkbox") {
            item.value = row.diamondMetadata[item.key] === "true";
          } else {
            item.value = row.diamondMetadata[item.key];
          }

          if (item.key === "openDailyAutoSalary" && item.value === "true") {
            this.isOpenDailyAutoSalary = true;
          }
        });
      }

      this.form = resForm;
    },
    handleDelete(row) {
      const that = this;
      that
        .$confirm(
          this.$t("pages.regionConfig.confirm.delete"),
          this.$t("pages.regionConfig.confirm.title"),
          {
            type: "warning"
          }
        )
        .then(() => {
          that.listLoading = true;
          deleteRegionConfig(row.id).then(res => {
            that.listLoading = false;
            that.$opsMessage.success();
            that.renderData();
          });
        })
        .catch(() => {});
    }
  }
};
</script>
