<template>
  <div class="app-container">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-select v-model="pagerDto._Eq_Id" placeholder="客户名称" clearable filterable>
          <el-option
            v-for="item in customers"
            :key="item.Id"
            :label="item.CompanyName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="pagerDto._Eq_SalesmanUserId" placeholder="业务员" clearable filterable>
          <el-option
            v-for="item in salesmanUser"
            :key="item.Id"
            :label="item.NickName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>

        <el-select class="customer-search" v-model="pagerDto._Eq_CompanyPossess" placeholder="客户所属"  clearable>
          <el-option
            v-for="item in companyPossess"
            :key="item.Value"
            :label="item.Name"
            :value="item.Value"
          />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-select class="customer-search" v-model="pagerDto._Eq_IsActive" placeholder="启用状态" clearable filterable>
          <el-option label="启用" value="True" />
          <el-option label="停用" value="False" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select class="customer-search" v-model="pagerDto._Eq_IsInterceptCustomers" placeholder="欠费拦截状态" clearable filterable>
          <el-option label="拦截" value="True" />
          <el-option label="不拦截" value="False" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select class="customer-search" v-model="pagerDto._Eq_Receiving" placeholder="收货状态" clearable filterable>
          <el-option label="收货" value="True" />
          <el-option label="停止收货" value="False" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select class="customer-search" v-model="pagerDto._Eq_VerificationSteps" placeholder="开户审批状态" clearable>
          <el-option v-for="item in verificationStepsList" :key="item.Value" :label="item.Name" :value="item.Value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="small" type="primary" :loading="ladding" @click="pagerSerach()">搜索</el-button>
        <el-button icon="el-icon-plus" size="small" plain type="primary">
          <router-link :to="{name:'CustomerEdit',params:{Id:0}}">添加客户</router-link></el-button>
        <el-button icon="el-icon-search" size="small" type="success" plain @click="outData()">导出</el-button>

      </el-form-item>
    </el-form>

    <el-table
      :data="sData"
      border
      height="660"
    >
      <el-table-column label="客户编码" prop="CustomerNumber">
        <template slot-scope="r">
          {{ r.row.CustomerNumber }}
          <el-tag v-if="r.row.AgentIOSS" type="success" size="mini" effect="dark">代缴IOSS</el-tag>
          <el-tag v-if="r.row.ConvertUSDToEUR" type="success" size="mini" effect="dark">欧盟USD转EUR</el-tag>
          <el-tag v-if="!r.row.Receiving" type="danger" size="mini" effect="dark">停止收货</el-tag>
          <svg-icon v-if="r.row.IsBindQYWX" class-name="wechat-icon" icon-class="wechat" @click.stop="click" />
        </template>
      </el-table-column>
      <el-table-column label="客户名称" prop="CompanyName">
        <template slot-scope="r">
          {{ r.row.CompanyName }}
        </template>
      </el-table-column>
      <el-table-column label="结算公司" prop="StrSettlementCompany" />
      <el-table-column label="业务员" prop="SalesmanUserName" />
      <el-table-column label="联系人" prop="Contact" />
      <el-table-column label="对接平台" prop="DockingPlatformName" />
      <el-table-column label="拦截欠费" prop="IsInterceptCustomers">
        <template slot-scope="r">
          <el-tag v-if="r.row.IsInterceptCustomers">是</el-tag>
          <el-tag v-if="!r.row.IsInterceptCustomers" type="info">否</el-tag>
        </template>
        </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <div v-if="scope.row.VerificationSteps === 0">
            <el-tag type="warning">待客户补充数据</el-tag>
          </div>
          <div v-if="scope.row.VerificationSteps === 1">
            <el-button type="primary" size="mini" plain>
              <router-link :to="{name:'CustomerEdit',params:{Id:scope.row.Id}}">审核</router-link>
              <i class="el-icon-s-check el-icon--right"></i>
            </el-button>
          </div>
          <div v-if="scope.row.VerificationSteps === 2">
            <!-- <el-button size="mini">
              <router-link :to="{name:'CustomerEdit',params:{Id:scope.row.Id}}">编辑</router-link>
            </el-button>
            <el-button v-if="!scope.row.IsActive" size="mini" @click="Enable(scope.row.Id)">
              启用
            </el-button>
            <el-button v-if="scope.row.IsActive" size="mini" @click="Disable(scope.row.Id)">
              停用
            </el-button>
            <el-button v-if="scope.row.Receiving&IsFS()" size="mini" @click="stopReceiving(scope.row.Id)">
              停止收货
            </el-button>
            <el-button v-if="!scope.row.Receiving&IsFS()" size="mini" @click="startReceiving(scope.row.Id)">
              开始收货
            </el-button>
            <el-button v-if="scope.row.AgentIOSS&IsCMS()" type="danger" size="mini" @click="stopAgentIOSS(scope.row.Id)">
              停止代缴
            </el-button>
            <el-button v-if="!scope.row.AgentIOSS&IsCMS()" size="mini" type="success" @click="startAgentIOSS(scope.row.Id)">
              开始代缴
            </el-button> -->
            <!-- <el-popover
              ref="popover"
              placement="left"
              trigger="hover"
              content="客户下单时如果物品申报币种为EUR时，自动按照【财务-基础设置-客户汇率】当月EUR转USD汇率换算相关申报金额，并修改申报币种。"
              width="350"
            /> -->
            <!-- <el-button v-if="!scope.row.ConvertUSDToEUR&&IsFS()" slot="reference" v-popover:popover style="margin-left:10px" icon="el-icon-question" type="success" size="mini" @click="startConvertUSDToEur(scope.row.Id)">
              开启欧盟USD转EUR
            </el-button>
            <el-button v-if="scope.row.ConvertUSDToEUR&&IsFS()" slot="reference" v-popover:popover style="margin-left:10px" icon="el-icon-question" type="danger" size="mini" @click="stopConvertUSDToEur(scope.row.Id)">
              停止欧盟USD转EUR
            </el-button> -->
            <el-dropdown @command="handleChangeAction">
              <el-button size="mini">
                操作<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-popover
                ref="popover"
                placement="left"
                trigger="hover"
                content="客户下单时如果物品申报币种为EUR时，自动按照【财务-基础设置-客户汇率】当月EUR转USD汇率换算相关申报金额，并修改申报币种。"
                width="350"
              />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="'customerEdit_'+ scope.row.Id">
                  <el-button size="mini">
                    编辑
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="!scope.row.IsActive" :command="'customerEnable_'+ scope.row.Id">
                  <el-button size="mini" style="margin-top: 4px;">
                    启用
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.IsActive" :command="'customerStop_'+ scope.row.Id">
                  <el-button size="mini" style="margin-top: 4px;">
                    停用
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.Receiving&IsFS()" :command="'customerStopReceipt_'+ scope.row.Id">
                  <el-button size="mini" style="margin-top: 4px;">
                    停止收货
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="!scope.row.Receiving&IsFS()" :command="'customerEnableReceipt_'+ scope.row.Id">
                  <el-button size="mini" style="margin-top: 4px;">
                    开始收货
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item :command="'customerEditAccountPeriod_'+ scope.row.Id">
                  <el-button size="mini" style="margin-top: 4px;">
                    调整帐期
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.AgentIOSS&IsCMS()" :command="'stopProxyPayment_'+ scope.row.Id">
                  <el-button size="mini" type="danger" style="margin-top: 4px;">
                    停止代缴
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="!scope.row.AgentIOSS&IsCMS()" :command="'startProxyPayment_'+ scope.row.Id">
                  <el-button size="mini" type="success" style="margin-top: 4px;">
                    开始代缴
                  </el-button>
                </el-dropdown-item>

                <el-dropdown-item v-if="!scope.row.ConvertUSDToEUR&&IsFS()" v-popover:popover :command="'customerOpenEU_'+ scope.row.Id">
                  <el-button size="mini" type="success" style="margin-top: 4px;">
                    <i class="el-icon-question"></i>开启欧盟USD转EUR
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.ConvertUSDToEUR&&IsFS()" v-popover:popover :command="'customerStopEU_'+ scope.row.Id">
                  <el-button size="mini" type="danger" style="margin-top: 4px;">
                    <i class="el-icon-question"></i>停止欧盟USD转EUR
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-sizes="[30, 50, 100, 200]"
      :current-page="pagerDto.PageIndex"
      :page-size="pagerDto.PageSize"
      background
      layout="prev, pager, next ,total ,jumper,sizes,slot "
      :total="pagerDto.total"
      @current-change="pagerSerach"
      @size-change="sizeChange"
    />
    <!-- 调整帐期 -->
    <el-dialog
      title="调整帐期"
      width="800px"
      custom-class="custom-account-period"
      :close-on-click-modal="false"
      :visible.sync="dialogAccountPeriodVisible"
      :before-close="handleCloseAccountPeriod">
      <div>
        <el-form
          ref="accountPeriodFormRef"
          label-width="95px"
          :rules="rulesAccountPeriod"
          :model="dtoAccountPeriod"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerId">
                <el-select
                  v-model="dtoAccountPeriod.customerId"
                  placeholder="选择客户名称"
                  clearable
                  filterable
                  disabled
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in customers"
                    :key="item.Id"
                    :label="item.CompanyName"
                    :value="item.Id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="帐期类型" prop="accountPeriod">
                <el-select
                  v-model="dtoAccountPeriod.accountPeriod"
                  placeholder="选择帐期类型"
                  clearable
                  filterable
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in accountPeriodTypeList"
                    :key="item.Label"
                    :label="item.Label"
                    :value="item.Value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="帐期额度" prop="accountingPeriodLimit">
                <el-input-number v-model="dtoAccountPeriod.accountingPeriodLimit" :controls="false" :min="0" style="width: 100%;"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结账类型" prop="checkoutTypes">
                <el-select
                  v-model="dtoAccountPeriod.checkoutTypes"
                  placeholder="选择结账类型"
                  style="width: 100%;"
                  @change="changeCheckoutTypes"
                >
                  <el-option
                    v-for="item in checkoutTypesList"
                    :key="item.Label"
                    :label="item.Label"
                    :value="item.Value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isShowCheckoutDays">
              <el-form-item label="结账天数" prop="checkoutDays">
                <el-input-number v-model="dtoAccountPeriod.checkoutDays" :controls="false" :min="0" :max="90" style="width: 100%;"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseAccountPeriod">取 消</el-button>
        <el-button type="primary" :loading="accountPeriodLoading" @click="hanleSubmitAccountPeriod">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { _queryPager, _disable, _enable, _getSalesmanUsers, _startAgentIOSS,
  _stopAgentIOSS, _startConvertUSDToEur, _stopConvertUSDToEur, _startReceiving, _stopReceiving
  , _outCustomer, _getAccountPeriod, _updateAccountPeriod
}
from '@/api/customer'
import { _getBillingCycle, _getCustomers, _getVerificationSteps, _getNSMPBillingCycle } from '@/api/baseInfo'

import { mapGetters } from 'vuex'
export default {
  name: 'CustomerSetting',
  computed: {
    ...mapGetters(['roles'])
  },
  data() {
    return {
      ladding: false,
      sData: [],
      customers: [],
      row: {},
      pagerDto:
            {
              PageIndex: 1,

              PageSize: 30,
              total: 0,
              _In_TrackingNumber: '',
              QuerySort: [{ Field: 'Id', IsDesc: true }],
              _Eq_Id: '',
              _Eq_IsActive: 'True',
              _Eq_SalesmanUserId: '',
              _Eq_CompanyPossess:0,
              _Eq_VerificationSteps: undefined,
            },
      salesmanUser: [],
      companyPossess: [
        { Name: '行运易', Value: 0 },
        { Name: '朗天', Value: 1 },
        { Name: '运控', Value: 2 },
        { Name: '集通' , Value:3}
      ],
      verificationStepsList: [],
      dialogAccountPeriodVisible: false,
      isShowCheckoutDays: false,
      accountPeriodLoading: false,
      dtoAccountPeriod: {
        id: undefined,
        customerId: undefined,
        accountPeriod: undefined,
        accountPeriodName: undefined,
        accountingPeriodLimit: undefined,
        checkoutDays: undefined,
        checkoutTypes: 0,
        checkoutTypesName: undefined,
      },
      accountPeriodTypeList: [],
      checkoutTypesList: [
        { Value: 0, Label: '根据账期生成' },
        { Value: 1, Label: '手工填写' },
      ],
      rulesAccountPeriod: {
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        accountPeriod: [
          { required: true, message: '请选择账期类型', trigger: 'change' }
        ],
        checkoutTypes: [
          { required: true, message: '请选择结账类型', trigger: 'change' }
        ],
        accountingPeriodLimit: [
          { required: true, message: '请输入账期额度', trigger: 'blur' }
        ],
        checkoutDays: [
          { required: true, message: '请输入结账天数', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    _getCustomers().then(response => {
      this.customers = response
    })

    _getSalesmanUsers().then(response => {
      this.salesmanUser = response
      this.pagerSerach()
    })

    _getVerificationSteps().then((res) => {
      this.verificationStepsList = res
    })

    // _getBillingCycle().then((response) => {
    //   this.billingCycle = response
    // })
    _getNSMPBillingCycle().then((res) => {
      this.accountPeriodTypeList = res
    })
  },
  methods: {
    sizeChange(PageSize) {
      this.pagerDto.PageSize = PageSize
      this.pagerSerach(1)
    },
    outData() {
      _outCustomer(this.pagerDto)
    },
    edit(row, column, event) {
      this.$router.push({ name: 'CustomerEdit', params: { Id: row.Id }})
    },
    IsCMS() {
      for (var i = 0; i < this.roles.length; i++) {
        if (this.roles[i] == '客服经理') {
          return true
        }
      }
      return false
    },
    IsFS() {
      for (var i = 0; i < this.roles.length; i++) {
        if (this.roles[i] == '财务') {
          return true
        }
      }
    },
    IsAdmin() {
      for (var i = 0; i < this.roles.length; i++) {
        if (this.roles[i] == '销售主管') {
          return true
        }
      }
      return false
    },
    stopAgentIOSS(id) {
      this.$confirm('确定停止代缴IOSS?').then(r => {
        _stopAgentIOSS(id).then(r => { this.pagerSerach() })
      })
    },
    startAgentIOSS(id) {
      this.$confirm('确定开始代缴IOSS?').then(r => {
        _startAgentIOSS(id).then(r => { this.pagerSerach() })
      })
    },
    stopReceiving(id) {
      this.$confirm('确定禁止收货?').then(r => {
        _stopReceiving(id).then(r => { this.pagerSerach() })
      })
    },
    startReceiving(id) {
      this.$confirm('确定开启收货?').then(r => {
        _startReceiving(id).then(r => { this.pagerSerach() })
      })
    },
    startConvertUSDToEur(id) {
      this.$confirm('开启欧盟USD转EUR?').then(r => {
        _startConvertUSDToEur(id).then(r => { this.pagerSerach() })
      })
    },
    stopConvertUSDToEur(id) {
      this.$confirm('停止欧盟USD转EUR?').then(r => {
        _stopConvertUSDToEur(id).then(r => { this.pagerSerach() })
      })
    },
    pagerSerach(index) {
      if (index) {
        this.pagerDto.PageIndex = index
      }
      this.ladding = true
      _queryPager(this.pagerDto).then(response => {
        this.sData = response.Result
        this.ladding = false
        this.pagerDto.total = response.TotalCount
        for (var j = 0; j < this.salesmanUser.length; j++) {
          for (var i = 0; i < response.Result.length; i++) {
            if (response.Result[i].SalesmanUserId == this.salesmanUser[j].Id) {
              response.Result[i].SalesmanUserName = this.salesmanUser[j].NickName
            }
          }
        }
      }).catch(response => {
        this.ladding = false
      })
    },
    Disable(id) {
      _disable(id).then(res => {
        this.$message('修改成功')
        this.pagerSerach()
      })
    },
    Enable(id) {
      _enable(id).then(res => {
        this.$message('修改成功')
        this.pagerSerach()
      })
    },
    handleChangeAction(command) {
      const action = command.split('_')[0]
      const Id = command.split('_')[1]

      switch (action) {
        case "customerEdit":
          this.$router.push({
            name: 'CustomerEdit',
            params: { Id }
          })
          break;
        case "customerEnable":
          this.Enable(Id)
          break;
        case "customerStop":
          this.Disable(Id)
          break;
        case "customerStopReceipt":
          this.stopReceiving(Id)
          break;
        case "customerEnableReceipt":
          this.startReceiving(Id)
          break;
        case "stopProxyPayment":
          this.stopAgentIOSS(Id)
          break;
        case "startProxyPayment":
          this.startAgentIOSS(Id)
          break;
        case "customerEditAccountPeriod":
          _getAccountPeriod(Id).then((res) => {
            if (res.code === 200) {
              this.dtoAccountPeriod = res.data
            }
          }).finally(() => {
            this.dialogAccountPeriodVisible = true
            const checkoutTypes = this.dtoAccountPeriod.checkoutTypes >= 0 ? this.dtoAccountPeriod.checkoutTypes : 0
            this.changeCheckoutTypes(checkoutTypes)
          })
          break;
        case "customerOpenEU":
          this.startConvertUSDToEur(Id)
          break;
        case "customerStopEU":
          this.stopConvertUSDToEur(Id)
          break;
        default:
          break;
      }
    },
    changeCheckoutTypes(val) {
      // 根据账期生成
      if(val === 0) {
        this.isShowCheckoutDays = false
        this.dtoAccountPeriod.checkoutDays = undefined
      } else {
        this.isShowCheckoutDays = true
      }
    },
    handleCloseAccountPeriod() {
      this.isShowCheckoutDays = false
      this.dialogAccountPeriodVisible = false
      this.$refs['accountPeriodFormRef'].resetFields()
      this.dtoAccountPeriod.checkoutTypes = 0
    },
    hanleSubmitAccountPeriod() {
      this.$refs['accountPeriodFormRef'].validate((valid) => {
        if (valid) {
          this.accountPeriodLoading = true
          _updateAccountPeriod(this.dtoAccountPeriod).then((res) => {
            this.$message.success('帐期更新成功')
            this.handleCloseAccountPeriod()
          }).finally(() => {
            this.accountPeriodLoading = false
          })
        } else {
          return false
        }
      })
    }
  }

}
</script>
<style>
.wechat-icon {
  color: #07c160;
}
.customer-search {
  width: 152px;
}
.custom-account-period .el-input__inner {
  text-align: left;
}
</style>
