<template>
  <div>
    <div>
      <el-tabs v-model="activeName" @tab-click="handleClick">

        <el-tab-pane label="客户总览" name="manage">
          <el-form :inline="true" :model="filterForm" class="filter-form" label-width="110px" :label-position="labelPosition">
            <el-tag>客户总数：共 <b>{{total}}</b> 个需求方客户</el-tag>
            <el-row>
              <el-form-item label="客户来源">
                <el-radio-group v-model="filterForm.source" size="mini">
                  <el-radio-button :label="0">全部</el-radio-button>
                  
                  <el-radio-button v-for="itm in counter.source" :label="itm.id" :key="itm.id">{{itm.name}}（{{itm.counter}}）</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="是否发布过项目">
                <el-radio-group v-model="filterForm.is_publish" size="mini">
                  <el-radio-button :label="0">全部</el-radio-button>
                  <el-radio-button :label="4">发布过（{{counter.published}}）</el-radio-button>
                  <el-radio-button :label="5">未发布过（{{counter.unpublished}}）</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="客户类别">
                <el-radio-group v-model="filterForm.type" size="mini">
                  <el-radio-button :label="0">全部</el-radio-button>
                  <el-radio-button :label="1">企业客户（{{counter.company}}）</el-radio-button>
                  <el-radio-button :label="2">个人客户（{{counter.personal}}）</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="注册时间">
                <el-date-picker
                  size="small"
                  style="width: 360px;"
                  v-model="timeRange"
                  type="daterange"
                  align="left"
                  unlink-panels
                  range-separator="到"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="客户经理">
                <el-radio-group v-model="filterForm.manager" size="mini">
                  <el-radio-button :label="0">全部</el-radio-button>
                  <el-radio-button v-for="itm in managerList" :label="itm.uid" :key="itm.uid">{{itm.nickname}}（{{itm.counter}}）</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchManage()" size="small">查询</el-button>
              </el-form-item>
              <el-form-item style="float: right;margin-right: 20px;">
                <el-button @click="exportList" type="primary" size="small">导出报表</el-button>
              </el-form-item>
            </el-row>
          </el-form>
          <el-table :data="manageData" border >
            <el-table-column label="用户">
              <template slot-scope="scope">
                <span class="lblue point">
                  <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.uid">{{scope.row.nickname}}</a>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="user_from" label="来源"></el-table-column>
            <el-table-column prop="company_name" label="企业信息"></el-table-column>
            <el-table-column prop="customer_type" label="客户类别"></el-table-column>
            <el-table-column label="企业背景">
              <template slot-scope="scope">
                <span class="lblue point" v-if="scope.row.customer_id">
                  <a target="_blank" :href="'https://www.tianyancha.com/search?key='+scope.row.customer_name">{{scope.row.customer_name}}</a>
                </span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column label="地区">
              <template slot-scope="scope">
                <span>{{scope.row.province}}</span>
                <span>{{scope.row.city}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="mobile" label="联系方式">
              <template slot-scope="scope">
                <span>手机：{{scope.row.mobile}}</span>
                <br>
                <span>微信：{{scope.row.weixin}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="logintime" label="注册时间"></el-table-column>
            <el-table-column prop="count_total" label="发布项目数"></el-table-column>
            <el-table-column prop="outcome" label="总托管费用"></el-table-column>
            <el-table-column prop="obj_id" label="客户经理">
              <template slot-scope="scope">
                <span class="lblue point">
                  <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.manager_id">{{scope.row.manager_nickname}}</a>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template slot-scope="scope">
                <div>{{ scope.row.remark_text }}</div>
                <el-button type="text" @click="onToList(scope.row.uid, 6)">查看备注({{ scope.row.remark_num }})</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="onRemark(scope.row.uid, 6)">添加备注</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="客户经理评级" name="grade">
          <el-table :data="gradeData" border style="width: 100%">
            <el-table-column
              prop=""
              label="评价者">
              <template slot-scope="scope">
          <span class="lblue point">
            <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.user_id">{{
                scope.row.user_id_name + '(' + scope.row.user_id + ')'
              }}</a>
          </span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="被评价者">
              <template slot-scope="scope">
          <span class="lblue point">
            <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.manager_uid">{{
                scope.row.manager_uid_name + '(' + scope.row.manager_uid + ')'
              }}</a>
          </span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="评价等级">
              <template slot-scope="scope">
                <span class="lblue point">
                   <el-rate :value="scope.row.grade" disabled></el-rate>
                </span>
                <span>
                  {{ scope.row.grade_name }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="评价标签">
              <template slot-scope="scope">
                <span v-for="item in scope.row.labels" style="margin-left: 5px">
                  <el-tag size="mini" type="info">{{ item }}</el-tag>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="评价时间">
              <template slot-scope="scope">
                <span>{{ formatDate(scope.row.create_time, 'Y-m-d H:i') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="更换客户经理" name="change">
          <el-table :data="changeData" border style="width: 100%">
            <el-table-column
              prop=""
              label="申请者">
              <template slot-scope="scope">
          <span class="lblue point">
            <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.apply_uid">{{
                scope.row.apply_uid_name + '(' + scope.row.apply_uid + ')'
              }}</a>
          </span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="原客户经理">
              <template slot-scope="scope">
          <span class="lblue point">
            <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.before_uid"
               v-if="scope.row.before_uid != '0'">{{
                scope.row.before_uid_name + '(' + scope.row.before_uid + ')'
              }}</a>
            <a href="javascript:;" v-else>-</a>
          </span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="更换后客户经理">
              <template slot-scope="scope">
          <span class="lblue point">
            <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.this_uid"
               v-if="scope.row.this_uid != '0'">{{
                scope.row.this_uid_name + '(' + scope.row.this_uid + ')'
              }}</a>
             <a href="javascript:;" v-else>-</a>
          </span>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="申请时间">
              <template slot-scope="scope">
                <span>{{ formatDate(scope.row.create_time, 'Y-m-d H:i') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status ===  '0'">待处理</span>
                <span v-else-if="scope.row.status ===  '1'">已处理</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template slot-scope="scope">
                <div>{{ scope.row.remark_text }}</div>
                <el-button type="text" @click="onToList(scope.row.id, 4)">查看备注({{ scope.row.remark_num }})</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="onRemark(scope.row.id, 4)">添加备注</el-button>
                <el-button type="text" v-if="scope.row.status === '0'" @click="onUpdateManager(scope.row)">立即处理
                </el-button>
                <el-button type="text" v-else disabled>已处理</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="客户经理管理" name="manager_info">
          <div class="mainTableTagbox">
            <el-tag>客户经理数： <b>{{total}}</b></el-tag>
            <el-tag>客户转化率： <b>{{managerInfoCounter.outcomeRate}}%</b></el-tag>
            <el-tag>待跟进项目数： <b>{{managerInfoCounter.pendingCount}}</b></el-tag>
          </div>
          <div style="margin-bottom:10px">
            <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="addManagerDialog = true">添加客户经理</el-button>
          </div>
          <el-table :data="managerInfo" border>
            <el-table-column label="用户">
              <template slot-scope="scope">
                <span class="lblue point">
                  <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.uid">{{scope.row.nickname}}</a>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="total_count" label="客户总数"></el-table-column>
            <el-table-column prop="month_achievment" label="本月业绩"></el-table-column>
            <el-table-column prop="outcome_rate" label="客户转化率">
              <template slot-scope="scope">
                <span >{{scope.row.outcome_rate}}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="pending_count" label="待跟进项目数"></el-table-column>
            <el-table-column prop="avg_grade" label="客户评分"></el-table-column>
            <el-table-column prop="status" label="当前状态">
              <template slot-scope="scope">
                <span :class="'status-' + scope.row.status">{{scope.row.status_name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="入职时间"></el-table-column>
            <el-table-column prop="leave_time" label="离职时间"></el-table-column>
            <el-table-column label="推荐人">
              <template slot-scope="scope">
                <span class="lblue point">
                  <a target="_blank" :href="scope.row.host+'/rooter/user/'+scope.row.creater_uid">{{scope.row.creater_nickname}}</a>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" v-if="scope.row.status != 2" @click="managerLeave(scope.row)">办理离职</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

    </div>

    <div class="page">
      <el-pagination
        class="order-footer"
        background
        layout="total, prev, pager, next"
        :page-size="20"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog title="添加备注" :visible.sync="remarkModel">
      <div>
        <el-input
          type="textarea"
          :rows="5"
          placeholder="请输入内容"
          v-model="remarkData.content">
        </el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="remarkModel = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="onRemarkSave">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加客户经理" :visible.sync="addManagerDialog" width="400px">
      <el-form :model="add_form" :label-position="labelPosition" label-width="100px">
        <el-form-item label="客户经理UID">
          <el-input v-model="add_form.uid"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="addManagerDialog = false">取消</el-button>
        <el-button size="medium" type="primary" @click="addManager">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="办理离职" :visible.sync="managerLeaveDialog" width="400px">
      <el-form :model="leave_form" :label-position="labelPosition" label-width="100px">
        <el-form-item label="交接客户">
          <el-select v-model="leave_form.change_uid" placeholder="请选择交接的客户经理">
            <el-option v-for="(itm, idx) of managerList" :label="itm.nickname" :key="idx" :value="itm.uid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="managerLeaveDialog = false">取消</el-button>
        <el-button size="medium" type="primary" @click="managerLeaveSubmit">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "user_cards_list",
  data() {
    return {
      page: 1,
      total: 0,
      loading: false,
      activeName: 'manage',
      remarkModel: false,
      remarkType: 6,
      remarkData: {id: '0', content: ''},
      labelPosition: 'left',
      gradeData: [],
      changeData: [],
      filterForm: {
        source: 0,
        is_publish: 0,
        manager:0,
        type:0
      },
      addManagerDialog: false,
      add_form: {
        uid: '',
      },
      managerLeaveDialog: false,
      leave_form: {
        uid: '',
        change_uid:''
      },
      managerList: [],
      managerInfoCounter: {pendingCount: 0, outcomeRate:0},
      manageData: [],
      counter: [],
      timeRange: [],
      managerInfo: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "全部",
            onClick(picker) {
              this.timeRange = [];
              picker.$emit("pick", []);
            }
          },
          {
            text: "最近7天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近30天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "本周",
            onClick(picker) {
              let week = new Date().getDay() - 1;
              if (week == -1) {
                week = 6;
              }
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * week);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "本月",
            onClick(picker) {
              let month = new Date().getMonth + 1;
              let year = new Date().getFullYear();
              let day = new Date().getDate() - 1;

              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * day);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "本年",
            onClick(picker) {
              let month = new Date().getMonth + 1;
              let year = new Date().getFullYear();
              let day = new Date().getDate() - 1;
              let firstDay = new Date(year, 0, 1);
              let dateDiff = new Date() - firstDay;
              let msPerDay = 1000 * 60 * 60 * 24;
              //计算天数
              let diffDays = Math.ceil(dateDiff / msPerDay) - 1;
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * diffDays);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
    }
  },
  mounted() {
    this.getData();
    this.getManagerList();
    this.getCounter();
  },
  methods: {
    getData() {
      if (this.activeName === 'change') {
        this.getChangeList();
      }else if(this.activeName === 'grade') {
        this.getGradeList();
      }else if(this.activeName === 'manage') {
        this.getManageList();
      }else if(this.activeName === 'manager_info') {
        this.getManagerInfoList();
      }
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
      this.getData();
    },
    async getChangeList() {
      const page = this.page;
      const data = {
        page
      };
      let res = await this.$post("/api/admin/accountManager/getChangeManagerList", data);
      if (res && res.status === 1) {
        this.changeData = res.data.list || [];
        this.total = res.data.total * 1;
      }
    },
    async getGradeList() {
      const page = this.page;
      const data = {
        page
      };
      let res = await this.$post("/api/admin/accountManager/getGradeList", data);
      if (res && res.status === 1) {
        this.gradeData = res.data.list || [];
        this.total = res.data.total * 1;
      }
    },
    async getManageList() {
      const page = this.page;
      const data = {
        page,
        source: this.filterForm.source,
        manager: this.filterForm.manager,
        is_publish: this.filterForm.is_publish,
        type: this.filterForm.type
      };
      if (this.timeRange != null) {
        data.start_time = this.timeRange[0];
        data.end_time = this.timeRange[1];
      }
      console.log(this.timeRange);
      let res = await this.$post("/api/admin/accountManager/getUserList", data);
      if (res && res.status === 1) {
        this.manageData = res.data.list || [];
        this.total = res.data.total * 1;
      }
    },
    async getManagerList() {
      let res = await this.$post("/api/admin/accountManager/getManagers");
      if (res && res.status === 1) {
        this.managerList = res.data;
      }
    },
    async getManagerInfoList() {
      const page = this.page;
      const data = {
        page
      };
      let res = await this.$post("/api/admin/accountManager/managerInfo", data);
      if (res && res.status === 1) {
        this.managerInfo = res.data.list || [];
        this.total = res.data.total * 1;
        this.managerInfoCounter.pendingCount = res.data.total_pending_count;
        this.managerInfoCounter.outcomeRate = res.data.total_outcome_rate;
      }
    },
    async addManager() {
      let res = await this.$post("/api/admin/accountManager/managerAdd", {
        uid: this.add_form.uid
      });
      if (res && res.status === 1) {
        this.getManagerInfoList();
        this.$message.success('添加成功')
        this.addManagerDialog = false;
      }
    },
    managerLeave(row) {
      this.leave_form.uid = row.uid;
      this.managerLeaveDialog = true;
    },
    managerLeaveSubmit() {
      this.$post("/api/admin/accountManager/managerLeave", this.leave_form).then(res => {
        if (res && res.status === 1) {
          this.getManagerInfoList();
          this.$message.success('设置成功')
          this.managerLeaveDialog = false;
        }
      });
    },
    searchManage() {
      this.page = 1;
      this.getManageList();
    },
    async exportList() {
      window.location.href = '/api/admin/accountManager/exportUserList?download=1' + 
        '&source=' + this.filterForm.source + '&manager=' + this.filterForm.manager+ '&is_publish=' + this.filterForm.is_publish;
    },
    onRemark(id, type) {
      this.remarkData.id = id;
      this.remarkType = type;
      this.remarkModel = true;
    },
    onToList(id, type) {
      let data = {
        obj_id: id,
        type: type
      }
      this.$router.push({path: '/main/remark_list', query: data});
    },
    async onRemarkSave() {
      this.loading = true;
      if (this.remarkData.content === '' || this.remarkData.id === '0') {
        this.$message.error('请输入内容')
        this.loading = false
        return false
      }

      let data = {content: this.remarkData.content, id: this.remarkData.id, type:this.remarkType}
      let res = await this.$post("/api/admin/accountManager/saveRemark", data);
      if (res && res.status === 1) {
        this.$message.success('备注成功')
        this.remarkModel = false
        this.getData()
      }
      this.loading = false
    },
    async onUpdateManager(row) {
      let data = {id: row.id}
      let res = await this.$post("/api/admin/accountManager/updateManager", data);
      if (res && res.status === 1) {
        this.$message.success('已备注')
        this.getData();
      }
    },
    async getCounter(row) {
      let res = await this.$post("/api/admin/accountManager/getUserCount");
      if (res && res.status === 1) {
        this.counter = res.data;
      }
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getData();
    },
    formatDate(time, format = '') {
      if (time === "0") {
        return "--";
      }
      let now = new Date(time * 1000);
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let date = now.getDate();
      let hour = now.getHours();
      let minute = now.getMinutes();
      let second = now.getSeconds();
      if (hour < 10) {
        hour = "0" + hour;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      return (format == '' ?
          year +
          "-" +
          month +
          "-" +
          date +
          " " +
          hour +
          ":" +
          minute +
          ":" +
          second
          :
          year +
          "-" +
          month +
          "-" +
          date +
          " " +
          hour +
          ":" +
          minute
      );
    },

  }

}
</script>

<style scoped>

.page {
  margin-top: 10px;
}
.el-form-item{
  margin-bottom: 0;
}
.filter-form{
  margin-bottom: 10px;
}
.mainTableTagbox{
  margin-bottom: 15px;
}
.status-1 {
  color:#409EFF;
}
.status-2 {
  color:#909399;
}
</style>
