<template>
  <div class="team-bill-settle-drawer">
    <el-drawer
      :visible="true"
      :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 slot="title" class="flex-l">
        <sys-origin-icon :icon="row.sysOrigin" size="18px" />&nbsp;{{ $t('pages.teamBill.settleDrawer.title') }} <el-button :loading="calculatorLoading" type="text" @click="reloadCalculator"><i v-if="!calculatorLoading" class="el-icon-refresh cursor-pointer" /></el-button>
      </div>
      <div class="team-bill-settle">
        <div class="drawer-form">
          <!-- <div v-if="row.details"> -->
          <div class="blockquote">{{ $t('pages.teamBill.settleDrawer.policyCalculation') }}
            <el-tooltip class="item" effect="dark">
              <div slot="content">
                <p>{{ $t('pages.teamBill.settleDrawer.policyTips.calculate') }}</p>
                <p>{{ $t('pages.teamBill.settleDrawer.policyTips.workMembers') }}</p>
                <p>{{ $t('pages.teamBill.settleDrawer.policyTips.policyBasis') }}</p>
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
          </div>
          <div class="content">
            <div class="flex-b bill-row">
              <div class="left bill-col nowrap-ellipsis">
                {{ $t('pages.teamBill.label.workMembers') }}: {{ calculatorRes.workMembers }}
              </div>
              <div class="right bill-col nowrap-ellipsis">
                {{ $t('pages.teamBill.label.finishMembers') }}:  {{ calculatorRes.finishMembers }}
              </div>
            </div>

            <div class="flex-b bill-row">
              <div class="left bill-col nowrap-ellipsis">
                {{ $t('pages.teamBill.label.memberSalaryUsd') }}: {{ calculatorRes.memberSalary }}
              </div>
              <div class="right bill-col nowrap-ellipsis">
                {{ $t('pages.teamBill.label.agentSalaryUsd') }}: {{ calculatorRes.ownSalary }}
              </div>
            </div>

            <div class="flex-b bill-row">
              <div class="right bill-col nowrap-ellipsis">
                {{ $t('pages.teamBill.label.totalSalaryUsd') }}: {{ calculatorRes.totalSalary }}
              </div>
            </div>

          <!-- </div> -->
          </div>

          <div class="blockquote">{{ $t('pages.teamBill.settleDrawer.settlement') }}
            <el-tooltip class="item" effect="dark">
              <div slot="content">
                <p>{{ $t('pages.teamBill.settleDrawer.settleTips.region') }}</p>
                <p>{{ $t('pages.teamBill.settleDrawer.settleTips.policy') }}</p>
                <p>{{ $t('pages.teamBill.settleDrawer.settleTips.payee') }}</p>
                <p>{{ $t('pages.teamBill.settleDrawer.settleTips.type') }}</p>
                <p>{{ $t('pages.teamBill.settleDrawer.settleTips.voucher') }}</p>
                <p>{{ $t('pages.teamBill.settleDrawer.settleTips.remarks') }}</p>
              </div>
              <i class="el-icon-info" />
            </el-tooltip>
          </div>
          <el-form ref="form" :model="form" :rules="formRules" label-width="80px" style="margin-right: 15px;">

            <el-form-item prop="region" :label="$t('pages.teamBill.label.region')">
              <select-system-region
                ref="regionSelectPolicy"
                v-model="form.region"
                :sys-origin="row.sysOrigin"
                :placeholder="$t('pages.teamBill.placeholder.selectRegion')"
                :disabled="calculatorLoading"
                @change="changeRegion"
              />
            </el-form-item>

            <el-form-item prop="policyId" :label="$t('pages.teamBill.label.policy')">
              <policy-select-sys-region
                ref="PolicySelectedSysRegion"
                v-model="form.policyId"
                :sys-origin="nativeRow.sysOrigin"
                :region="region"
                :placeholder="$t('pages.teamBill.placeholder.selectPolicy')"
                :disabled="calculatorLoading"
                @change="cahngePolicy"
              />
            </el-form-item>

            <!-- <el-form-item prop="bankCardId" label="收款">
              <bank-card-select
                ref="BankCardSelect"
                v-model="form.bankCardId"
                :user-id="row.userId"
                placeholder="请选择收款"
                @change="changeBankCard"
              />
            </el-form-item> -->

            <el-form-item prop="settleType" :label="$t('pages.teamBill.label.type')">
              <el-select
                v-model="form.settleType"
                :placeholder="$t('pages.teamBill.placeholder.selectSettleType')"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in teamBillSettleTypes"
                  :key="index"
                  :label="teamBillSettleTypeName(item.value)"
                  :value="item.value"
                />
              </el-select>

            </el-form-item>

            <el-form-item v-if="form.settleType === 'GOLD' || form.settleType === 'MONEY_GOLD'" prop="goldQuantity" :label="$t('pages.teamBill.label.gold')">
              <el-input v-model="form.goldQuantity" v-number :placeholder="$t('pages.teamBill.placeholder.goldQuantity')" />
            </el-form-item>

            <el-form-item v-if="form.settleType === 'MONEY_GOLD'" prop="salaryQuantity" :label="$t('pages.teamBill.label.salaryUsd')">
              <el-input v-model="form.salaryQuantity" v-double :placeholder="$t('pages.teamBill.placeholder.salaryQuantity')" />
            </el-form-item>

            <el-form-item prop="tmpExistsCertificate" :label="$t('pages.teamBill.label.voucherUpload')">
              <el-row>
                <el-col :span="8">
                  <upload-image
                    v-model="certificateOne"
                    :file-dir="$application.fileBucket.back"
                  />
                </el-col>
                <el-col :span="8">
                  <upload-image
                    v-model="certificateTwo"
                    :file-dir="$application.fileBucket.back"
                  />
                </el-col>
                <el-col :span="8">
                  <upload-image
                    v-model="certificateThree"
                    :file-dir="$application.fileBucket.back"
                  />
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item :label="$t('pages.teamBill.label.remarks')">
              <el-input
                v-model="form.remarks"
                type="textarea"
                :placeholder="$t('pages.teamBill.placeholder.remarks')"
                maxlength="100"
                show-word-limit
                resize="none"
                rows="5"
              />
            </el-form-item>
          </el-form>
        </div>

        <div v-if="!calculatorLoading" class="drawer-footer">
          <el-button :disabled="submitLoading" @click="handleClose()">{{ $t('pages.teamBill.action.close') }}</el-button>
          <el-button type="primary" :disabled="submitLoading" :loading="submitLoading" @click="submit">{{ $t('pages.teamBill.action.save') }}</el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>
<script>
import { teamBillSettle, getTeamBillCalculator } from '@/api/team'
import { teamBillSettleTypes } from '@/constant/team-type'
import { deepClone } from '@/utils'
import PolicySelectSysRegion from './../components/PolicySelectSysRegion'
import BankCardSelect from './../components/BankCardSelect'

export default {
  name: 'TeamBillSettle',
  components: { PolicySelectSysRegion, BankCardSelect },
  props: {
    row: {
      type: Object,
      require: true,
      default: () => {}
    }
  },
  data() {
    const commonRules = [
      { required: true, message: this.$t('pages.teamBill.validation.requiredField'), trigger: 'blur' }
    ]
    return {
      calculatorLoading: false,
      calculatorRes: {},
      correctWagesVisible: false,
      rewardCheckBoxVisible: false,
      deductCheckBoxVisible: false,
      teamBillSettleTypes,
      submitLoading: false,
      certificateOne: '',
      certificateTwo: '',
      certificateThree: '',
      form: {
        id: '',
        teamId: '',
        region: '',
        policyId: '',
        bankCardId: '',
        settleType: '',
        goldQuantity: '',
        salaryQuantity: '',
        remarks: '',
        certificateUrls: [],
        tmpExistsCertificate: '',
        bankCardArchives: {
          id: '',
          teamId: '',
          cardType: '',
          payee: '',
          cardNo: ''
        }
      },
      region: '',
      formRules: {
        id: commonRules,
        teamId: commonRules,
        policyId: commonRules,
        region: commonRules,
        bankCardId: commonRules,
        settleType: commonRules,
        goldQuantity: commonRules,
        salaryQuantity: commonRules,
        tmpExistsCertificate: [
          { required: true, message: this.$t('pages.teamBill.validation.uploadVoucherFirst'), trigger: 'blur' }
        ]
      },
      nativeRow: {}
    }
  },
  computed: {
  },
  watch: {
    row: {
      handler(newVal) {
        if (newVal) {
          this.nativeRow = deepClone(newVal)
          this.form.id = this.nativeRow.id
          this.form.teamId = this.nativeRow.teamId
          this.form.region = this.nativeRow.region
          this.region = this.nativeRow.region
          // this.form.bankCardId = this.nativeRow.bankCardId
          this.form.settleType = this.nativeRow.settleType
          this.form.rewardSalary = this.nativeRow.rewardSalary
          this.form.remarks = this.nativeRow.remarks
          this.form.certificateUrls = []
          this.form.tmpExistsCertificate = ''
          this.loadTeamBillCalculator()
        }
      },
      immediate: true
    }
  },
  methods: {
    teamBillSettleTypeName(type) {
      return this.$t(`pages.teamBill.settleType.${type}`)
    },
    changeRegion(id, val) {
      this.region = id
      this.$refs.PolicySelectedSysRegion.clearValue()
      this.calculatorRes = {}
      this.form.actualSalary = 0
    },
    handleClose() {
      if (this.submitLoading) {
        this.$opsMessage.warn(this.$t('pages.teamBill.message.submitting'))
        return
      }
      this.$emit('close')
    },
    reloadCalculator() {
      this.loadTeamBillCalculator()
    },
    cahngePolicy() {
      this.form.actualSalary = 0
      this.loadTeamBillCalculator()
    },
    submit() {
      const that = this
      if (that.calculatorLoading) {
        this.$opsMessage.warn(this.$t('pages.teamBill.message.calculatingSalary'))
        return
      }

      that.form.certificateUrls = []
      if (that.certificateOne) {
        that.form.certificateUrls.push(that.certificateOne)
      }
      if (that.certificateTwo) {
        that.form.certificateUrls.push(that.certificateTwo)
      }
      if (that.certificateThree) {
        that.form.certificateUrls.push(that.certificateThree)
      }
      that.form.tmpExistsCertificate = that.form.certificateUrls.length > 0 ? 'true' : ''

      that.form.workMembers = that.calculatorRes.workMembers
      that.form.finishMembers = that.calculatorRes.finishMembers
      that.form.memberSalary = that.calculatorRes.memberSalary
      that.form.ownSalary = that.calculatorRes.ownSalary
      that.form.totalSalary = that.calculatorRes.totalSalary
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        that.submitLoading = true
        teamBillSettle(that.form).then(res => {
          that.submitLoading = false
          this.$emit('success', that.form)
        }).catch(er => {
          that.submitLoading = false
        })
      })
    },
    loadTeamBillCalculator() {
      const that = this
      that.calculatorLoading = true
      getTeamBillCalculator({
        billId: that.row.id,
        policyId: that.form.policyId
      }).then(res => {
        that.calculatorLoading = false
        that.calculatorRes = res.body || {}
        that.form.policyId = that.calculatorRes.policyId
        that.form.actualSalary = that.calculatorRes.totalSalary
      }).catch(er => {
        that.calculatorLoading = false
        console.error(er)
      })
    },
    changeBankCard(id, card) {
      this.form.bankCardArchives = card
    },
    changeCorrectWages(val) {
      if (val === false) {
        this.form.actualSalary = this.calculatorRes.totalSalary || 0
      }
    }
  }
}
</script>
<style scoped lang="scss">
.team-bill-settle {
  .content {
    margin-bottom: 10px;
    .bill-row {
      padding: 10px 0px;
      >.bill-col {
        width: 50%;
      }
    }
  }
}
</style>

