<template>
  <div class="app-container-region">

    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        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"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </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" />国家与语言Code文档</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="区域编码" align="center" />
      <el-table-column prop="regionName" label="区域" align="center" />
      <el-table-column label="国家" align="center" prop="countryCodes" min-width="200" />
      <el-table-column label="语言" align="center" prop="langeCodes" min-width="100" />
      <el-table-column prop="remarks" label="备注" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" align="center" width="50">
        <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)">修改</el-dropdown-item>
              <el-dropdown-item @click.native="clickCopyRegionId(scope.row)">复制ID</el-dropdown-item>
              <el-dropdown-item @click.native="clickResetWithdrawal(scope.row)">重置提现</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="textOptTitle + '('+listQuery.sysOrigin+')'"
      :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" :model="form" :rules="rules" label-width="110px">
            <el-form-item label="区域编码" prop="regionCode">
              <el-input v-model.trim="form.regionCode" :disabled="form.id !== ''" placeholder="区域编码(慎重填写,不可修改)" maxlength="20" show-word-limit />
            </el-form-item>
            <el-form-item label="区域名称" prop="regionName">
              <el-input v-model.trim="form.regionName" placeholder="请输入区域名称" maxlength="50" show-word-limit />
            </el-form-item>
            <el-form-item label="国家" prop="countryCodes">
              <el-input v-model.trim="form.countryCodes" placeholder="如:CN,IN多个使用英语逗号分隔" maxlength="200" show-word-limit />
            </el-form-item>
            <el-form-item label="语言" prop="langeCodes">
              <el-input v-model.trim="form.langeCodes" placeholder="如:ar,en多个使用英语逗号分隔" maxlength="200" show-word-limit />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model.trim="form.remarks" type="textarea" placeholder="请输入备注" maxlength="200" rows="5" resize="none" show-word-limit />
            </el-form-item>
            <el-form-item prop="withdrawalWaysList" label="提现方式">
              <el-select v-model="form.withdrawalWaysList" multiple placeholder="请选择" 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="美金$钱包设置">
              <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="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'">
                    {{ item.label }}
                  </el-checkbox>
                  <el-tooltip :content="item.describe">
                    <i class="el-icon-info" />
                  </el-tooltip>
                </div>
              </el-row>
            </el-form-item>

            <el-form-item label="钻石钱包设置">
              <div v-if="listQuery.sysOrigin === 'YOLO'" style="color: red;">
                YOLO其余配置-共用美金钱包的配置
              </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'">
                    {{ item.label }}
                  </el-checkbox>
                  <el-tooltip :content="item.describe">
                    <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()">保存</el-button>
          <el-button @click="handleClose()">取消</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'

function getFormData() {
  return {
    id: '',
    sysOrigin: '',
    regionCode: '',
    langeCodes: '',
    countryCodes: '',
    remarks: '',
    regionName: '',
    withdrawalWays: '',
    withdrawalWaysList: [],
    metadatas: [
      { key: 'walletVisible', value: false, label: '开启钱包', describe: '开启钱包后当前区域用户都可以使用钱包功能(显示钱包模块)', type: 'checkbox' },
      { key: 'agentWalletVisible', value: false, label: '代理钱包', describe: '在区域钱包关闭情况下,代理角色能使用钱包', type: 'checkbox' },
      { key: 'hostSalaryToAgent', value: false, label: '主播工资结算代理钱包', describe: '将主播工资结算到代理钱包中, 否则将结算到主播自己的钱包', type: 'checkbox' },
      { key: 'openExchangeGold', value: false, label: '允许钱包兑换金币', describe: '允许使用钱包 “兑换金币” 功能(显示兑换金币按钮)', type: 'checkbox' },
      { key: 'openTransfer', value: false, label: '允许钱包转账', describe: '允许使用钱包 “转账” 功能(显示转账按钮)', type: 'checkbox' },
      { key: 'openWithdraw', value: false, label: '允许钱包提现', describe: '未勾允许使用钱包 “提现” 功能 (显示提现按钮)', type: 'checkbox' },
      { key: 'openDiamondExchangeGold', value: false, label: '开启钻石兑换金币', describe: '接收幸运礼物可以获得钻石,开启此功能则用户可以使用钻石兑换金币', type: 'checkbox' },
      { key: 'openTeamDelHost', value: false, label: '开启代理删除主播权限', describe: '开启之后该区域下的代理将可以删除自己名下主播', type: 'checkbox' },
      { key: 'openHostApplyQuitTeam', value: false, label: '开启主播申请解约权限', describe: '开启之后该区域下的主播将可以发起与代理解约申请', type: 'checkbox' },
      { key: 'openBankCardMenu', value: false, label: '显示银行卡菜单', describe: '勾选,用户则可以看到该菜单', type: 'checkbox' },
      { key: 'openKycMenu', value: false, label: '显示KYC菜单', describe: '勾选,用户则可以看到该菜单', type: 'checkbox' },
      { key: 'openDailyAutoSalary', value: 'false', label: '开启日结工资模式', describe: '请慎重选择,一旦开启[日结模式]后将停止使用[月结工资], 且无法恢复回[月结模式]', type: 'radio' }
    ],
    diamondMetadatas: [
      { key: 'walletVisible', value: false, label: '开启钱包', describe: '开启钱包后当前区域用户都可以使用钱包功能(显示钱包模块)', type: 'checkbox' },
      { key: 'agentWalletVisible', value: false, label: '代理钱包', describe: '在区域钱包关闭情况下,代理角色能使用钱包', type: 'checkbox' },
      { key: 'hostSalaryToAgent', value: false, label: '主播工资结算代理钱包', describe: '将主播工资结算到代理钱包中, 否则将结算到主播自己的钱包', type: 'checkbox' },
      { key: 'openExchangeGold', value: false, label: '允许钱包兑换金币', describe: '允许使用钱包 “兑换金币” 功能(显示兑换金币按钮)', type: 'checkbox' },
      { key: 'openTransfer', value: false, label: '允许钱包转账', describe: '允许使用钱包 “转账” 功能(显示转账按钮)', type: 'checkbox' },
      { key: 'openWithdraw', value: false, label: '允许钱包提现', describe: '未勾允许使用钱包 “提现” 功能 (显示提现按钮)', type: 'checkbox' },
      { key: 'openDailyAutoSalary', value: 'false', label: '开启日结工资模式', describe: '请慎重选择,一旦开启[日结模式]后将停止使用[月结工资], 且无法恢复回[月结模式]', type: 'radio' }
    ],
    metadata: {},
    diamondMetadata: {}
  }
}
export default {
  name: 'RegionConfig',
  data() {
    return {
      list: [],
      bankCardTypes,
      listQuery: {
        sysOrigin: 'HALAR'
      },
      formVisible: false,
      isOpenDailyAutoSalary: false,
      textOptTitle: '',
      form: getFormData(),
      submitLoading: false,
      rules: {
        sysOrigin: [
          { required: true, message: '必填字段不可为空', trigger: 'blur' }
        ],
        regionName: [
          { required: true, message: '必填字段不可为空', trigger: 'blur' }
        ],
        regionCode: [
          { required: true, message: '必填字段不可为空', trigger: 'blur' }
        ]
        // langeCodes: [
        //   { required: true, message: '请填写区域', trigger: 'blur' }
        // ],
        // countryCodes: [
        //   { required: true, message: '必填字段不可为空', trigger: 'blur' }
        // ]
      },
      listLoading: true
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  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.textOptTitle = '添加'
      this.isOpenDailyAutoSalary = false
      this.form = getFormData()
    },
    clickResetWithdrawal(row) {
      const that = this
      that.$confirm('是否确定重置, 该区域的团队用户将可重新发起?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetRegionWithdrawal(row.id).then(res => {
          that.$message({
            type: 'success',
            message: 'Successful'
          })
          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.textOptTitle = '修改'
      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('确认删除吗？(会同步删除区域辅助数据)', '提示', {
        type: 'warning'
      }).then(() => {
        that.listLoading = true
        deleteRegionConfig(row.id).then((res) => {
          that.listLoading = false
          that.$opsMessage.success()
          that.renderData()
        })
      }).catch(() => {

      })
    }
  }
}
</script>
