<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.nickName" clearable class="filter-item" style="width: 200px" placeholder="请输入达人昵称" />
      <el-input v-model="listQuery.talentId" clearable class="filter-item" style="width: 200px" placeholder="请输入达人ID" />
      <el-input v-model="listQuery.tel" clearable class="filter-item" style="width: 200px" placeholder="请输入达人手机号" />
      <el-input v-model="listQuery.provider" clearable class="filter-item" style="width: 200px" placeholder="请输入服务商" />
      <el-date-picker v-model="timeArray" type="datetimerange" class="filter-item" style="width:320px" range-separator="至"
        start-placeholder="加入开始日期" end-placeholder="加入结束日期" :picker-options="{}" value-format="yyyy-MM-dd HH:mm:ss" />


      <el-button v-permission="['GET /admin/kstalent/talentList']" class="filter-item" type="primary"
        icon="el-icon-search" @click="handleFilter(false)">查找
      </el-button>
      <el-button v-permission="['POST /admin/kstalent/addNewTalent']" class="filter-item" type="primary"
        icon="el-icon-edit" @click="addTalent">添加达人
      </el-button>
      <el-button v-permission="['GET /admin/kstalent/talentList']" class="filter-item" type="primary"
        icon="el-icon-download" @click="handleFilter(true)">下载
      </el-button>
      <el-button v-permission="['POST /admin/kstalent/batchAdd']" class="filter-item" type="primary" icon="el-icon-upload"
        @click="importVisible = true">批量导入
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="id" prop="id" type="index" fixed />
      <el-table-column align="center" label="服务商" prop="provider" />
      <el-table-column align="center" label="快手id" prop="talentId" />
      <el-table-column align="center" label="达人昵称" prop="nickName" />
      <el-table-column align="center" label="手机号" prop="tel" />

      <el-table-column align="center" label="状态" prop="deleted">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleted ? 'warning' : ''">{{ scope.row.deleted && scope.row.deleted ? '停用' : '启用'
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="备注" prop="remark" />

      <el-table-column align="center" label="加入时间" prop="createTime" />
      <el-table-column align="center" label="最后操作时间" prop="updateTime" />

      <el-table-column align="center" label="操作" width="150">
        <template slot-scope="scope">

          <el-button v-permission="['POST /admin/dytalent/delete']" v-if="!scope.row.deleted" type="text"
            icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          <el-button v-permission="['POST /admin/dytalent/updateTalent']" type="text" icon="el-icon-edit" size="mini"
            @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getList" />


    <!-- 添加达人 -->
    <el-dialog :visible.sync="addVisible" :title="updateStatus ? '修改达人' : '添加达人'" width="650px">
      <el-form ref="addForm" :rules="addRules" :model="addForm" status-icon label-position="left" label-width="100px"
        style="width:400px; margin-left:50px;">
        <el-form-item label="服务商" prop="provider">
          <el-input v-model="addForm.provider" style="width:100%" />
        </el-form-item>
        <el-form-item label="达人id" prop="talentId">
          <el-input v-model="addForm.talentId" style="width:100%" />
        </el-form-item>
        <el-form-item label="达人昵称" prop="nickName">
          <el-input v-model="addForm.nickName" style="width:100%" />
        </el-form-item>

        <el-form-item label="手机号" prop="tel">
          <el-input v-model="addForm.tel" maxlength="11" style="width:100%" />
        </el-form-item>

        <el-form-item label="标签" prop="tag">
          <el-input v-model="addForm.tag" style="width:100%" maxlength="11" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" style="width:100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" v-if="updateStatus" @click="handleRealUpdate()">确定</el-button>
        <el-button type="primary" v-else @click="handleAdd()">确定</el-button>
      </div>
    </el-dialog>


    <!-- 达人批量导入 -->
    <el-dialog :visible.sync="importVisible" title="达人批量导入">
      <el-form ref="importForm" status-icon label-position="left" label-width="100px"
        style="width: 800px; margin-left:50px;">
        <div style="color:red;margin:10px 0">导入excel格式:服务商,达人id,达人昵称,达人手机号，标签</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="excel导入">
              <input id="im" type="file" @change="getFile($event)" ref="file" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button v-permission="['POST /admin/dytalent/batchAdd']" class="filter-item" type="primary"
              icon="el-icon-upload2" @click="importConfirm">导入</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="importResult" fit highlight-current-row>
        <el-table-column align="center" label="服务商" prop="provider" />
        <el-table-column align="center" label="达人id" prop="talentId" />
        <el-table-column align="center" label="达人昵称" prop="nickName" />
        <el-table-column align="center" label="手机号" prop="tel" />
        <el-table-column align="center" label="导入结果" prop="result" />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importVisible = false">确定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { addNewTalent, talentList, updateTalent, importTalent, deleteTalentList,talentDownload } from "@/api/ksTalent";
import Pagination from "@/components/Pagination";

let vm;
export default {
  name: "ksTalent",
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        nickName: '',
        provider: '',
        isExport: false
      },
      timeArray: [],
      updateStatus: false,
      importResult: [],
      importVisible: false,
      addForm: {
        talentId: '',
        nickName: '',
        tel: '',
        remark: ""
      },
      addVisible: false,
      updateVisible: false,
      addRules: {
        talentId: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
        nickName: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
        tel: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, {
          pattern: /^1[3456789]\d{9}$/,
          message: '请输入正确的手机号码',
          trigger: 'blur'
        }],
      },
    };
  },
  created() {
    this.handleFilter(false);
  },
  methods: {
    handleRealUpdate() {
      updateTalent(this.addForm).then(() => {
        this.addVisible = false;
        this.addForm = {};
        this.$notify.success({
          title: '成功',
          message: '修改成功'
        });
        this.getList();
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: '修改失败'
        });
      });
    },
    handleUpdate(data) {
      console.log("data==>" + JSON.stringify(data));
      this.addVisible = true;
      this.updateStatus = true;
      this.addForm = {
        id: data.id,
        provider: data.provider,
        tag: data.tag,
        talentId: data.talentId,
        nickName: data.nickName,
        tel: data.tel,
        remark: data.remark
      };
    },
    fraBindingChange(row) {
      updateTalent(row).then(res => {
        this.$notify.success({
          title: '成功',
          message: '修改成功'
        });

      })

    },
    getFile: function (event) {
      this.file = event.target.files[0];
      console.log(this.file);
    },
    importConfirm() {
      if (!this.file) {
        this.$message.warning("请选择文件！");
        return;
      }
      if (this.file.name.lastIndexOf("xlsx") < 0) {
        this.$message.warning("请选择excel文件！");
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: "文件导入中，请耐心等待...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      var formData = new window.FormData(); // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'
      formData.append("file", this.file);


      importTalent(formData)
        .then((res) => {
          console.log("导入返回数据", res);
          // let element = document.getElementById("im");
          // element.outerHTML=element.outerHTML;

          this.$refs.file.value = null;
          this.file = null;

          loading.close();
          if (res.data.errno == 0) {
            this.$message.success(res.data.errmsg);
            console.info(res.data.data);
            if (res.data.data.length >= 1) {
              this.importVisible = true;
              this.importResult = res.data.data;
              this.showdownloading = true;
            }
          } else {
            this.$message.warning(res.data.errmsg);
          }
        })
        .catch((err) => {
          this.$refs.file.value = null;
          this.file = null;


          loading.close();
          this.$message.warning(err.data.errmsg);
        });
    },
    handleFilter(isExport) {
      if (isExport == false)
        this.listQuery.pageNum = 1;
      this.listQuery.isExport = isExport;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      if (this.timeArray && this.timeArray.length === 2) {
        this.listQuery.start = this.timeArray[0];
        this.listQuery.end = this.timeArray[1];
      } else {
        this.listQuery.start = null;
        this.listQuery.end = null;
      }

      if (!this.listQuery.isExport) {
        talentList(this.listQuery)
          .then((response) => {
            this.listLoading = false;
            console.info("查询")
            this.list = response.data.data.list;
            this.total = response.data.data.total;
            this.listLoading = false;
          })
          .catch((res) => {
            this.list = [];
            this.total = 0;
            this.listLoading = false;
          });
      }
      else {
        talentDownload(this.listQuery)
          .then((res) => {
            this.listLoading = false; 
            let blob = new Blob([res.data], {
              type: "application/vnd.ms-excel",
            });
            console.log(blob)
            let fileName = "快手达人.xlsx";
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, fileName);
            } else {
              var link = document.createElement("a");
              link.href = window.URL.createObjectURL(blob);
              link.download = fileName;
              link.click();
              //释放内存
              window.URL.revokeObjectURL(link.href);
            }
          });
      }

    },
    addTalent() {
      this.addVisible = true;
      this.addForm = {
        talentId: '',
        nickName: '',
        tel: '',
        remark: ''
      };
      this.updateStatus = false;
    },
    handleAdd() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          addNewTalent(this.addForm).then(response => {

            this.addVisible = false;
            this.$notify.success({
              title: '成功',
              message: '添加成功'
            });
            this.getList();

          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },

    handleDelete(row) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteTalentList(row)
          .then((response) => {
            this.$notify.success({
              title: "成功",
              message: "删除成功",
            });
            this.handleFilter(false);
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg,
            });
          });
      });
    },
  },
  beforeCreate() {
    vm = this;
  },

};
</script>
<style scoped>
.el-form-item {
  margin-bottom: 18px;
}
</style>
