<template>
  <div class="app-container">
    <div>
      <el-form inline :model="pagerDto">
        <el-form-item label="渠道">
          <el-select
            v-model="pagerDto._Eq_ChannelId"
            placeholder="渠道"
            clearable
            filterable
          >
            <el-option
              v-for="item in channels"
              :key="'channel1' + item.Id"
              :value="item.Id"
              :label="item.Name"
            />
          </el-select>
          <el-form-item label="国家" prop="CountryCodeValues" style="margin-left: 20px">
            <el-select v-model="pagerDto._Eq_CountryCode" filterable clearable>
              <el-option
                v-for="(item, index) in countries"
                :key="index"
                :label="item.CnName"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="模式">
            <el-select v-model="searchMode">
              <el-option
                v-for="(item, index) in modes"
                :key="index"
                :label="item.key"
                :value="item.value"
              />
            </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            icon="el-icon-search"
            size="small"
            type="primary"
            @click="pagerSerach(1)"
          >搜索</el-button>
          <el-button
            icon="el-icon-circle-plus-outline"
            size="small"
            type="success"
            @click="showAddPanel"
          >新增</el-button>
          <el-button
            icon="el-icon-circle-plus-outline"
            size="small"
            type="success"
            @click="showBatchImport=true"
          >批量导入</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table v-loading="loading" border :data="sourceData">
        <el-table-column label="渠道" prop="ChannelName" />
        <el-table-column label="国家">
          <template slot-scope="scope">
            {{ `${scope.row.CountryName}(${scope.row.CountryCode})` }}
          </template>
        </el-table-column>
        <el-table-column label="电话" prop="Phone" />
        <el-table-column label="创建时间" prop="CreateTime" />
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" plain @click="remove(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        :page-sizes="[20, 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="handleSizeChange"
      />
    </div>
    <el-dialog :visible.sync="showEditPannel">
      <el-form
        ref="editForm"
        v-loading="submiting"
        label-width="6em"
        :model="editItem"
        :rules="rules"
      >
        <el-form-item label="渠道" prop="ChannelId">
          <el-select v-model="editItem.ChannelId" filterable>
            <el-option
              v-for="item in channels"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="国家" prop="Country">
          <el-select v-model="editItem.CountryCode" filterable>
            <el-option
              v-for="(item, index) in countries"
              :key="index"
              :label="item.CnName"
              :value="item.Code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editItem.Phone" />
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button size="large" type="success" @click="validtAndSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      :visible.sync="showBatchImport"
      title="批量上传电话"
      @closed="uploadClosed"
    >
      <div v-loading="uploading" style="text-align: center">
        <el-upload
          ref="upload"
          accept=".xlsx"
          :action="uploadUrl"
          :file-list="fileList"
          :auto-upload="false"
          :headers="headers"
          :on-success="uploadSuccess"
          :on-error="uploadError"
        >
          <el-button
            slot="trigger"
            size="small"
            type="primary"
          >选择文件</el-button>
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
          >上传到服务器</el-button>

          <el-link
            type="primary"
            :href="templateUrl"
            style="margin-left: 20px"
          >下载模板</el-link>

          <div slot="tip" class="el-upload__tip">只能上传.xlsx文件</div>
        </el-upload>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="showUploadError"
      title="导入错误"
      @closed="fileList = []"
    >
      <div>
        <div v-for="(msg, idx) in errorMsgs" :key="idx" style="color:red">{{ msg }}</div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { _getDeliverChannel } from '@/api/baseInfo'
import { _getCountries } from '@/api/baseInfo'
import request from '@/utils/request'
import { getToken } from '@/utils/auth'

export default {
  name: 'ChannelPhone',
  data() {
    return {
      searchMode:0,
      modes:[{key:'搜索有电话',value:0},{key:'搜索无电话',value:1}],
      uploading: false,
      showUploadError: false,
      errorMsgs: [],
      fileList: [],
      showBatchImport: false,
      templateUrl: 'http://wms.xingyunyi.cn/Data/Template/ChannelPhone.xlsx',

      submiting: false,
      editMode: '',
      editItem: {
        Id: null,
        ChannelId: null,
        CountryCode: null,
        Phone: null
      },
      showEditPannel: false,
      loading: false,
      channels: [],
      countries: [],
      sourceData: [],
      pagerDto: {
        _Eq_ChannelId: null,
        _Eq_CountryCode: null,
        QuerySort: [{ 'Field': 'Id', 'IsDesc': true }],
        PageIndex: 1,
        PageSize: 20,
        total: 100
      },
      rules: {
        ChannelId: { required: true, message: '请选择渠道', trigger: 'blur' },
        CountryCode: {
          required: true,
          message: '请选择国家',
          trigger: 'blur'
        },
        Phone: {
          required: true,
          message: '请填写电话',
          trigger: 'blur'
        }
      }
    }
  },
  computed: {
    uploadUrl() {
      return `${process.env.VUE_APP_BASE_API}/channelPhone/batchImport`
    },
    headers() {
      const token = getToken()
      return {
        token: token
      }
    }
  },
  created() {
    _getDeliverChannel().then((resp) => {
      this.channels = resp
    })
    this.getCountries()
    this.pagerDto.PageIndex = 1
    this.pagerDto._Eq_ChannelId = ''
    this.queryData()
  },
  methods: {
    submitUpload() {
      this.uploading = true
      this.$refs.upload.submit()
    },
    uploadClosed() {
      this.$refs.upload.clearFiles()
    },
    uploadSuccess(response, file, fileList) {
      const data = response.Data
      if (!!data && data.length > 0) {
        this.errorMsgs = data
        this.showUploadError = true
      } else {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.pagerDto.PageIndex = 1
        this.pagerDto._Eq_ChannelId = ''
        this.queryData()
      }
      this.showBatchImport = false
      this.uploading = false
    },
    uploadError(err, file, fileList) {
      this.$message({
        message: err.message,
        type: 'error'
      })
      this.showBatchImport = false
      this.uploading = false
    },
    validtAndSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.submit()
        } else {
          return false
        }
      })
    },
    edit(item) {
      this.editMode = 'edit'
      this.showEditPannel = true
      this.editItem.Id = item.Id
      this.editItem.ChannelId = item.ChannelId
      this.editItem.CountryCode = item.CountryCode
      this.editItem.Phone = item.Phone
    },
    remove(item) {
      this.$confirm('是否删除该电话?', '正在删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        request({
          url: '/channelPhone/remove',
          params: { id: item.Id },
          method: 'post'
        })
          .then((resp) => {
            if (resp === true) {
              const idx = this.sourceData.findIndex((i) => i.Id === item.Id)
              this.sourceData.splice(idx, 1)
            } else {
              const msg = resp.message
              this.$message(msg)
            }
          })
          .catch(() => {
            this.$message('删除出错')
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    submit() {
      let url = '/channelPhone/create'
      let op = '新增'
      if (this.editMode === 'edit') {
        url = '/channelPhone/modify'
        op = '修改'
      }
      this.submiting = true
      request({
        url: url,
        data: this.editItem,
        method: 'post'
      })
        .then((resp) => {
          if (resp.success === true) {
            this.showEditPannel = false
            this.initEditItem()
            this.$alert(`${op}成功`, `${op}成功`, {
              confirmButtonText: '确定',
              callback: () => {
                this.queryData()
              }
            })
          } else {
            const msg = resp.message
            this.$message(msg)
          }
        })
        .finally(() => {
          this.submiting = false
        })
    },
    showAddPanel() {
      this.editMode = 'add'
      this.initEditItem()
      this.showEditPannel = true
    },
    initEditItem() {
      this.showEditPannel = false
      this.editItem.Id = null
      this.editItem.ChannelId = null
      this.editItem.CountryCode = null
      this.editItem.Phone = null
    },
    handleSizeChange(size) {
      this.pagerDto.PageSize = size
      this.queryData()
    },
    pagerSerach(page) {
      this.pagerDto.PageIndex = page
      this.queryData()
    },
    getCountries() {
      _getCountries().then((resp) => {
        this.countries = resp
      })
    },
    queryData() {
      let url='/channelPhone/query';
      if(this.searchMode==1){
        url='/channelPhone/queryNoPhones';
      }
      this.loading = true
      request({
        url ,
        method: 'post',
        data: this.pagerDto
      })
        .then((resp) => {
          this.loading = false
          this.pagerDto.total = resp.TotalCount
          this.pagerDto.PageIndex = resp.PageIndex

          this.sourceData = resp.Result
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>
