<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.nickName" clearable class="filter-item" style="width: 150px" placeholder="请输入达人昵称" />
      <el-input v-model="listQuery.talentId" clearable class="filter-item" style="width: 160px" placeholder="请输入达人ID" />
      <el-input v-model="listQuery.tel" clearable class="filter-item" style="width: 155px" placeholder="请输入达人手机号" />
      <el-input v-model="listQuery.provider" clearable class="filter-item" style="width: 160px" 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-select v-model="listQuery.isSnow" clearable class="filter-item" style="width: 170px" placeholder="请选择是否开小雪花">
        <el-option label="开启" :value="1"></el-option>
        <el-option label="未开启" :value="0"></el-option>
      </el-select>

      <el-select v-model="listQuery.channelId" clearable class="filter-item" style="width: 170px" placeholder="请选择达人渠道">
        <el-option label="抖音-鲸致" :value="26"></el-option>
        <el-option label="抖音-云嘉" :value="107"></el-option>
      </el-select>

      <el-input v-model="listQuery.operator" clearable class="filter-item" style="width: 160px" placeholder="请输入达运" />

      <el-select v-model="listQuery.source" clearable class="filter-item" style="width: 170px" placeholder="请选择资源来源">
        <el-option label="个人开拓" value="个人开拓"></el-option>
        <el-option label="公司资源" value="公司资源"></el-option>
        <el-option label="组长分配" value="组长分配"></el-option>
      </el-select>

      <el-select v-model="listQuery.sourceType" clearable class="filter-item" style="width: 170px" placeholder="请选择资源类型">
        <el-option label="独立达人" value="独立达人"></el-option>
        <el-option label="团长" value="团长"></el-option>
        <el-option label="机构" value="机构"></el-option>
      </el-select>

      <el-input v-model="listQuery.sourceLeader" clearable class="filter-item" style="width: 160px" placeholder="请输入团长或结构名称" />


      <el-button v-permission="['GET /admin/dytalent/talentList']" class="filter-item" type="primary"
        icon="el-icon-search" @click="handleFilter">查找
      </el-button>
      <el-button v-permission="['POST /admin/dytalent/addNewTalent']" class="filter-item" type="primary"
        icon="el-icon-edit" @click="addTalent">添加
      </el-button>
      <el-button v-permission="['POST /admin/dytalent/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 width="100" />
      <el-table-column align="center" label="达人信息" prop="provider">
        <template slot-scope="scope">
          <div style="text-align: left;">
            <span style="font-weight: 600;">达人ID:</span><span> {{ scope.row.talentId }}</span><br />
            <span style="font-weight: 600;">达人昵称:</span><span> {{ scope.row.nickName }}</span><br />
            <span style="font-weight: 600;">达人手机:</span><span> {{ scope.row.tel }}</span><br />
            <span style="font-weight: 600;">达人渠道:</span><el-tag
              :type="scope.row.channelId == null || scope.row.channelId == 26 ? '' : 'info'"> {{
        scope.row.channelId == null || scope.row.channelId == 26 ? '抖音-鲸致' : '抖音-云嘉'
      }}</el-tag><br />
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="达运信息" prop="operator">

        <template slot-scope="scope">
          <div style="text-align: left;">
            <span style="font-weight: 600;">资源来源:</span> {{ scope.row.source }}<br />
            <span style="font-weight: 600;">资源类型:</span> {{ scope.row.sourceType }}<br />
            <span style="font-weight: 600;">团长或结构名称:</span> {{ scope.row.sourceLeader }}<br />
            <span style="font-weight: 600;">达运名称:</span> {{ scope.row.operator }}<br />
            <span style="font-weight: 600;">绑定日期:</span><span> {{ scope.row.bindDate }}</span><br />
            <span style="font-weight: 600;">解绑日期:</span><span> {{ scope.row.unbindDate }}</span><br />
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" prop="deleted">

        <template slot-scope="scope">
          <div style="text-align: left;">
            <span style="font-weight: 600;">启用状态:</span> <el-tag :type="scope.row.deleted ? 'warning' : ''">{{
        scope.row.deleted && scope.row.deleted ? '停用' : '启用' }}</el-tag><br />
            <span style="font-weight: 600;">小雪花入口:</span><el-switch v-model="scope.row.isSnow"
              @change="fraBindingChange(scope.row)" /><br />
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="其他信息" prop="operator">

        <template slot-scope="scope">
          <div style="text-align: left;">
            <span style="font-weight: 600;">备注:</span> {{ scope.row.remark }}<br />
            <span style="font-weight: 600;">录入时间:</span><span> {{ scope.row.createTime }}</span><br />
            <span style="font-weight: 600;">最后操作时间:</span><span> {{ scope.row.updateTime }}</span><br />
          </div>
        </template>
      </el-table-column>

      <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" placeholder="请输入达人的提供商" style="width:100%" />
        </el-form-item>&ndash;&gt;-->

        <el-form-item label="达人渠道" prop="channelId">
          <el-select v-model="addForm.channelId" clearable class="filter-item" style="width: 100%"
            :disabled="updateStatus&&addForm.channelId!=null" placeholder="请选择达人渠道">
            <el-option label="抖音-鲸致" :value="26"></el-option>
            <el-option label="抖音-云嘉" :value="107"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="达人id" prop="talentId">
          <el-input v-model="addForm.talentId" placeholder="请输入达人的抖音id" :disabled="updateStatus" style="width:100%" />
        </el-form-item>
        <el-form-item label="达人昵称" prop="nickName">
          <el-input v-model="addForm.nickName" style="width:100%" placeholder="请输入达人昵称" />
        </el-form-item>

        <el-form-item label="手机号" prop="tel">
          <el-input v-model="addForm.tel" maxlength="11" placeholder="请输入达人手机号" type="number" style="width:100%" />
        </el-form-item>

        <el-form-item label="资源来源" prop="source">
          <el-select v-model="addForm.source" clearable class="filter-item" style="width: 100%"
                     placeholder="请选择运资源来源">
            <el-option label="个人开拓" value="个人开拓"></el-option>
            <el-option label="公司资源" value="公司资源"></el-option>
            <el-option label="组长分配" value="组长分配"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资源类型" prop="sourceType">
          <el-select v-model="addForm.sourceType" clearable class="filter-item" style="width: 100%"
                     placeholder="请选择资源类型" @change="updateSourceType()">
            <el-option label="独立达人" value="独立达人"></el-option>
            <el-option label="团长" value="团长"></el-option>
            <el-option label="机构" value="机构"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="团长/机构名称" prop="sourceLeader" v-if="addForm.sourceType=='团长' || addForm.sourceType=='机构'">
          <el-input v-model="addForm.sourceLeader"   style="width:100%" />
        </el-form-item>



        <el-form-item label="达运名称" prop="operator">
          <el-input v-model="addForm.operator" placeholder="请输入达运名称" :disabled="operatorAbled" style="width:100%" />
        </el-form-item>

        <el-form-item label="绑定日期" prop="bindDate">
          <el-date-picker v-model="addForm.bindDate" :disabled="bindDateAbled" type="date" class="filter-item"
            placeholder="请选择与达运绑定日期" style="width:100%" :picker-options="{}" value-format="yyyy-MM-dd" />
        </el-form-item>

        <el-form-item label="解绑日期" prop="unbindDate">
          <el-date-picker v-model="addForm.unbindDate" :disabled="unbindDateAbled" type="date" class="filter-item"
            placeholder="请选择与达运解绑日期" style="width:100%" :picker-options="{}" value-format="yyyy-MM-dd" />
        </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、*达人昵称、*达人电话、*达资来源、*达资类型<br/>、团长或机构名、*达运姓名、*绑定日期、解绑日期。（*为必填）</div>
        <div style="color:red;margin:10px 0">归属平台品牌：抖音-鲸致、抖音-云嘉</div>
        <div style="color:red;margin:10px 0">达资来源：个人开拓、公司资源、组长分配</div>
        <div style="color:red;margin:10px 0">达资类型：独立达人、团长、机构</div>
        <div style="color:red;margin:10px 0">上传限制：单次批量上传 2000 条</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="channel" />
        <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="source" />
        <el-table-column align="center" label="达资类型" prop="sourceType" />
        <el-table-column align="center" label="团长或机构名" prop="sourceLeader" />
        <el-table-column align="center" label="达运姓名" prop="operator" />
        <el-table-column align="center" label="绑定日期" prop="bindDate" />
        <el-table-column align="center" label="解绑日期" prop="unbindDate" />
        <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>
        <el-button @click="handleDownload">结果导出</el-button>
      </div>
    </el-dialog>


  </div>
</template>

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

let vm;
export default {
  name: "Coupon",
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        nickName: '',
        provider: '',
        operator:''
      },
      timeArray: [],
      updateStatus: false,
      importResult: [],
      importVisible: false,
      addForm: {
        talentId: '',
        nickName: '',
        tel: '',
        remark: "",
        source:"",
        sourceType:"",
        sourceLeader:""
      },
      bindDateAbled: false,
      unbindDateAbled: false,
      operatorAbled: false,//是否可用
      addVisible: false,
      updateVisible: false,
      addRules: {
        talentId: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
        nickName: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
        operator: [{ required: true, message: '达运不能为空', trigger: 'blur' }],
        bindDate: [{ required: true, message: '绑定日期不能为空', trigger: 'blur' }],
        channelId: [{ required: true, message: '达人渠道不能为空', trigger: 'blur' }],
        tel: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, {
          pattern: /^1[3456789]\d{9}$/,
          message: '请输入正确的手机号码',
          trigger: 'blur'
        }],
        source: [{ required: true, message: '请选择运资源来源', trigger: 'blur' }],
        sourceType: [{ required: true, message: '请选择资源类型', trigger: 'blur' }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleRealUpdate() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          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,
        operator: data.operator,
        bindDate: data.bindDate,
        unbindDate: data.unbindDate,
        channelId: data.channelId,
        source: data.source,
        sourceType: data.sourceType,
        sourceLeader: data.sourceLeader
      };
      this.bindDateAbled = this.addForm.bindDate ? true : false;
      this.unbindDateAbled = this.addForm.unbindDate ? true : false;
      this.operatorAbled = this.addForm.operator ? true : false;
    },
    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);
            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() {
      this.listQuery.pageNum = 1;
      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;
      }

      talentList(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });

    },
    addTalent() {
      this.addVisible = true;
      this.addForm = {
        talentId: '',
        nickName: '',
        tel: '',
        remark: '',
        channelId: 26
      };
      this.updateStatus = false;
      this.unbindDateAbled = false;
      this.bindDateAbled = false;
      this.operatorAbled = 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();
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg,
            });
          });
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "渠道",
          "达人id",
          "达人昵称",
          "达人电话",
          "达资来源",
          "达资类型",
          "团长或机构名",
          "达运姓名",
          "绑定日期",
          "解绑日期",
          "导入结果"
        ];
        const filterVal = [
          "channel",
          "talentId",
          "nickName",
          "tel",
          "source",
          "sourceType",
          "sourceLeader",
          "operator",
          "bindDate",
          "unbindDate",
          "result"
        ];
        excel.export_json_to_excel2(tHeader, this.importResult, filterVal, "导入结果");
        this.downloadLoading = false;
      });
    },
    updateSourceType(){
      if (this.addForm.sourceType == '独立达人') {
        this.addForm.sourceLeader="";
      }
    }
  },
  beforeCreate() {
    vm = this;
  },
};
</script>

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