<template>
  <div class="app-container">
        <el-card  v-if="checkPermission(['company_view'])">
<div slot="header" class="clearfix">
    <span>单位</span>
  </div>
<el-table
          :data="tableDatac.results"
          style="width: 100%;"
          border
          fit
          v-loading="listLoadingc"
          highlight-current-row
          height="160"
          row-key="id"
          @row-click = 'handleCompanyClick'
        >
          <el-table-column label="单位名称">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
        </el-table>
    <pagination
      v-show="tableDatac.count>0"
      :total="tableDatac.count"
      :page.sync="listQueryc.page"
      :limit.sync="listQueryc.limit"
      @pagination="getListc"
    />

        </el-card>
        <el-card style="margin-top:6px">
          <div slot="header" class="clearfix">
    <span>学员</span>
  </div>
    <div>
      <el-select
        v-if="checkPermission(['admin'])"
        v-model="listQuery.create_admin"
        placeholder="创建账户"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in adminOptions"
          :key="item.id"
          :label="item.username + '/' + item.name"
          :value="item.id"
        />
      </el-select>
      <!-- <el-select
        v-model="listQuery.company"
        placeholder="所属单位"
        clearable
        filterable
        style="width: 200px"
        class="filter-item"
        @change="handleFilter"
        remote
        :remote-method="searchCompany"
      >
        <el-option
          v-for="item in companyData"
          :key="item.key"
          :label="item.label"
          :value="item.value"
        />
      </el-select> -->
      <el-select
        v-model="listQuery.role"
        placeholder="用户类型"
        clearable
        filterable
        style="width: 200px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in roleData"
          :key="item.key"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="datevalue"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
        :picker-options="pickerOptions"
      ></el-date-picker>
      <!-- <el-select
        v-model="listQuery.is_paid"
        placeholder="是否缴费"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in enabledOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>-->
      <el-input
        v-model="listQuery.search"
        placeholder="姓名/手机号/单位"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-refresh-left"
        @click="resetFilter"
      >重置</el-button>
    </div>
    <div style="margin-top:10px">
      
      <el-button type="primary" @click="handleAddUser" icon="el-icon-plus">新增</el-button>
      <el-popover
        type="primary"
        placement="top"
        width="160"
        v-if="checkPermission(['consumer_import'])"
        v-model="popovervisible"
      >
        <p>导入用户前,请下载模板并按格式录入.</p>
        <div style="text-align: left; margin: 0;">
          <el-link
            href="/media/muban/user.xlsx"
            target="_blank"
            @click="popovervisible = false"
            type="primary"
          >下载模板</el-link>
          <el-upload
            :action="upUrl"
            :on-success="handleUploadSuccess"
            accept=".xlsx"
            :headers="upHeaders"
            :show-file-list="false"
          >
            <el-button size="small" type="primary" @click="popovervisible = false">上传导入</el-button>
          </el-upload>
        </div>
        <el-button slot="reference" icon="el-icon-upload2">Excel导入</el-button>
      </el-popover>
      <el-button
        type="primary"
        icon="el-icon-download"
        @click="exportConsumer"
        v-if="checkPermission(['consumer__export'])"
      >导出Excel</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="handleDeletes"
        v-if="checkPermission(['consumer__deletes'])"
      >批量删除</el-button>
      <el-button
        @click="handleUpdateends"
        v-if="checkPermission(['consumer_exceeddates'])"
      >批量修改到期</el-button>
      <!-- <el-button
        type="primary"
        icon="el-icon-search"
        round
        @click="handleCands"
        v-if="checkPermission(['consumer__candidates'])"
      >批量查证</el-button> -->
      <el-checkbox
        v-model="showCreate"
        class="filter-item"
        style="margin-left:15px;"
        @change="tableKey=tableKey+1"
      >创建信息</el-checkbox>
    </div>
    
    <el-table
      :data="consumerList"
      style="width: 100%;margin-top:10px;"
      border
      fit
      v-loading="listLoading"
      highlight-current-row
      height="400"
      @sort-change="changeSort"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="手机号" sortable="custom" prop="username">
        <template slot-scope="scope">{{ scope.row.username }}</template>
      </el-table-column>
      <el-table-column label="用户类型">
        <template slot-scope="scope">{{ scope.row.role_name }}</template>
      </el-table-column>
      <el-table-column label="单位" sortable="custom" prop="company">
        <template
          slot-scope="scope"
          v-if="scope.row.company_name != null"
        >{{ scope.row.company_name }}</template>
      </el-table-column>
      <el-table-column label="工作类别" sortable="custom" prop="workscope">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.workscope_name">{{ scope.row.workscope_name }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="证书信息">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.workscope_name">{{ scope.row.workscope_name }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="创建信息" sortable="custom" prop="create_time" v-if="showCreate" >
        <template slot-scope="scope">
          <span v-if="scope.row.create_admin_">{{ scope.row.create_admin_.username }}/</span>
          <span>{{ scope.row.create_time.substring(0,10) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期日期">
        <template slot-scope="scope">{{ scope.row.exceed_date }}</template>
      </el-table-column>
      <el-table-column align="left" label="操作" fixed="right" width="260">
        <template slot-scope="scope">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope)"
              icon="el-icon-edit"
              v-if="checkPermission(['consumer_update'])"
            ></el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope)"
              icon="el-icon-delete"
              v-if="checkPermission(['consumer_delete'])"
            ></el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleUnbind(scope)"
              v-if="scope.row.username&&scope.row.openid&&checkPermission(['consumer_unbind'])"
            >解微</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
        </el-card>
        <el-dialog :visible.sync="dateVisible" title='修改截止期限'>
          <el-date-picker
      v-model="exceed_date"
      type="date"
      placeholder="选择日期"
      value-format="yyyy-MM-dd">
    </el-date-picker>
    <div style="text-align:right;">
        <el-button type="primary" @click="confirmupdateend">确认</el-button>
      </div>
        </el-dialog>
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'新增用户'">
      <el-form
        :model="consumer"
        label-width="80px"
        label-position="right"
        :rules="rule1"
        ref="consumerForm"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="consumer.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="username">
          <el-input v-model="consumer.username" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="单位" prop="company">
          <el-input placeholder="单位" v-model="consumer.company_.name" readonly>
            <el-button slot="append" icon="el-icon-search" @click="choose()"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="缴费学科" prop="subjects">
          <el-select v-model="consumer.subjects" placeholder="缴费学科" style="width:100%" multiple>
            <el-option
              v-for="item in subjectData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作类别" prop="workscope">
          <el-select v-model="consumer.workscope" placeholder="工作类别" style="width:100%" clearable>
            <el-option
              v-for="item in workscopeData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型" prop="role">
          <el-select v-model="consumer.role" placeholder="用户类型" style="width:100%" clearable>
            <el-option
              v-for="item in roleData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号过期" prop="exceed_date">
          <el-date-picker
      v-model="consumer.exceed_date"
      type="date"
      placeholder="选择日期"
      value-format="yyyy-MM-dd">
    </el-date-picker>
        </el-form-item>
        <el-form-item label="身份证号" prop="ID_number1">
          <el-input v-model="consumer.ID_number1" placeholder="身份证号" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUser('consumerForm')">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="选择企业"
      :visible.sync="dgVisiable"
      :close-on-click-modal="false"
      width="80%"
      :append-to-body="true"
    >
      <Companychose ref="Companychose" @handleChose="chooseComplete"></Companychose>
    </el-dialog>
  </div>
</template>

<script>
import {
  getConsumerList,
  createConsumer,
  deleteConsumer,
  updateConsumer,
  importConsumer,
  exportConsumer,
  deleteConsumers,
  unbindConsumer,
  getConsumerRoleAll,
  updateendConsumers
} from "@/api/crm";
import { getSubjectAll } from "@/api/question";
import { getWorkScopeAll } from "@/api/examtest";
import { getCompanyList } from "@/api/crm";
import { genTree, deepClone } from "@/utils";
import checkPermission from "@/utils/permission";
import { upUrl } from "@/api/file";
import { getUserList } from "@/api/user";
import { getToken } from "@/utils/auth";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Companychose from "@/views/crm/companychose";
const defaultConsumer = {
  id: "",
  name: "",
  username: "",
  company: null,
  company_: {},
  subjects: [],
  workscope: null,
  role: 3,
};
const listQuery = {
  page: 1,
  limit: 20,
  search: "",
};
export default {
  components: { Pagination, Companychose },
  watch: {
    filterOrgText(val) {
      this.$refs.tree.filter(val);
    },
  },
  data() {
    return {
      dateVisible:false,
      exceed_date:'',
      dgVisiable: false,
      tableKey: 0,
      showCreate: true,
      upUrl: upUrl(),
      popovervisible: false,
      consumer: defaultConsumer,
      upHeaders: { Authorization: "JWT " + getToken() },
      consumerList: [],
      total: 0,
      listLoading: true,
      listLoadingc: false,
      listQuery: {
        page: 1,
        limit: 20,
        search: "",
      },
      listQueryc: {
        page: 1,
        limit: 20,
        search: "",
      },
      tableDatac: {count:0},
      enabledOptions: [
        { key: "true", display_name: "已缴" },
        { key: "false", display_name: "未缴" },
      ],
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        username: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "change",
            pattern: /^1[3456789]\d{9}$/,
          },
        ],
        role: [{ required: true, message: "请选择", trigger: "change" }],
        workscope: [{ required: true, message: "请选择", trigger: "change" }],
        subjects: [{ required: true, message: "请选择", trigger: "change" }],
        exceed_date: [{ required: true, message: "请选择", trigger: "change" }],
      },
      filterOrgText: "",
      treeLoding: false,
      companyData: [],
      subjectData: [],
      workscopeData: [],
      roleData: [],
      selects: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            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) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      datevalue: "",
      adminOptions: [],
    };
  },
  computed: {},
  watch: {
    datevalue: "setTimeRange",
  },
  created() {
    this.getList();
    this.getListc();
    this.getSubjectAll();
    this.getWorkScopeAll();
    this.getConsumerRoleAll();
    this.getAdminOptions();
  },
  methods: {
    checkPermission,
    handleUploadSuccess(res, file) {
      if (res.code == 200) {
        const loading = this.$loading({ text: "正在导入中..." });
        importConsumer(res.data).then((response) => {
          loading.close();
          if (response.code == 200) {
            this.$message({
              message: "导入成功",
              type: "success",
            });
            this.getList(listQuery);
          } else if (response.code == 206) {
            this.$message({
              message: "部分未成功" + response.data,
              type: "success",
            });
            this.getList(listQuery);
          } else {
            this.$message.error(response.msg);
          }
        });
      } else {
        this.$message.error("Excel上传失败!");
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getList() {
      this.listLoading = true;
      getConsumerList(this.listQuery).then((response) => {
        this.consumerList = response.data.results;
        this.total = response.data.count;
        this.listLoading = false;
      });
    },
    getListc() {
      this.listLoadingc = true;
      getCompanyList(this.listQueryc).then((response) => {
        this.tableDatac = response.data;
        this.listLoadingc = false;
      });
    },
    // getCompanyList() {
    //   this.treeLoding = true;
    //   getCompanyList().then((response) => {
    //     this.companyData = genTree(response.data.results);
    //     this.treeLoding = false;
    //   });
    // },
    // searchCompany(val) {
    //   this.treeLoding = true;
    //   getCompanyList({ search: val, perm: "all" }).then((response) => {
    //     this.companyData = genTree(response.data.results);
    //     this.treeLoding = false;
    //   });
    // },
    getSubjectAll() {
      getSubjectAll().then((response) => {
        this.subjectData = genTree(response.data);
      });
    },
    getWorkScopeAll() {
      getWorkScopeAll().then((response) => {
        this.workscopeData = genTree(response.data);
      });
    },
    getConsumerRoleAll() {
      getConsumerRoleAll().then((response) => {
        this.roleData = genTree(response.data);
      });
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        limit: 20,
        search: "",
      };
      this.getList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleAddUser() {
      this.consumer = Object.assign({}, defaultConsumer);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["consumerForm"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.consumer = Object.assign({}, scope.row); // copy obj
      if (this.consumer.company_ == null) {
        this.consumer.company_ = {};
      }
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["consumerForm"].clearValidate();
      });
    },
    handleUnbind(scope) {
      this.$confirm("确认解除该账户的微信绑定吗!", "警告", {
        type: "warning",
      })
        .then(() => {
          unbindConsumer(scope.row.id)
            .then((res) => {
              this.$message({
                type: "success",
                message: "解绑成功!",
              });
              this.getList();
            })
            .catch((err) => {
              console.error(err);
            });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleDelete(scope) {
      this.$confirm("确认删除该用户吗?将丢失数据!", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteConsumer(scope.row.id);
          this.consumerList.splice(scope.row.index, 1);
          this.$message({
            type: "success",
            message: "成功删除!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleDeletes() {
      if (this.selects.length) {
        this.$confirm(
          "确认删除这" + this.selects.length + "位用户吗?将丢失数据!",
          "警告",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "error",
          }
        )
          .then(async () => {
            const { code } = await deleteConsumers({ ids: this.selects });
            if (code >= 200) {
              this.getList();
              this.$message({
                type: "success",
                message: "成功删除!",
              });
            }
          })
          .catch((err) => {
            console.error(err);
          });
      } else {
        this.$message({
          message: "请先选择",
          type: "warning",
        });
      }
    },
    async confirmUser(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            let consumer = this.consumer;
            updateConsumer(this.consumer.id, consumer).then((res) => {
              // for (let index = 0; index < this.consumerList.length; index++) {
              //   if (this.consumerList[index].id === this.consumer.id) {
              //     this.consumerList.splice(
              //       index,
              //       1,
              //       Object.assign({}, this.consumer)
              //     );
              //     break;
              //   }
              // }
              this.getList();
              this.dialogVisible = false;
                this.$message.success('成功')
              
            });
          } else {
            createConsumer(this.consumer).then((res) => {
              // this.consumer = res.data
              // this.consumerList.unshift(this.consumer)
              this.getList();
              this.dialogVisible = false;
                this.$message.success('成功')
            });
          }
        } else {
          return false;
        }
      });
    },
    exportConsumer() {
      const loading = this.$loading();
      exportConsumer(this.listQuery).then((response) => {
        loading.close();
        window.open(response.data.path, "_blank");
      }).catch(()=>{loading.close()});
    },
    changeSort(val) {
      if (val.order == "ascending") {
        this.listQuery.ordering = val.prop;
      } else {
        this.listQuery.ordering = "-" + val.prop;
      }

      this.getList();
    },
    handleSelectionChange(val) {
      let selects = [];
      for (var i = 0; i < val.length; i++) {
        selects.push(val[i].id);
      }
      this.selects = selects;
    },
    setTimeRange() {
      (this.listQuery.min_create = this.datevalue[0]),
        (this.listQuery.max_create = this.datevalue[1]),
        this.getList();
    },
    getAdminOptions() {
      if (checkPermission(["admin"])) {
        getUserList({pageoff:true}).then((res) => {
          this.adminOptions = res.data;
        });
      }
    },
    choose() {
      this.dgVisiable = true;
    },
    chooseComplete(val) {
      this.dgVisiable = false;
      if (val) {
        this.consumer.company_ = val;
        this.consumer.company = val.id;
      }
    },
    handleCompanyClick(row, column, event){
      this.listQuery.company = row.id
      this.getList()
    },
    handleUpdateends() {
      if (this.selects.length) {
        this.dateVisible = true
      } else {
        this.$message({
          message: "请先选择",
          type: "warning",
        });
      }
    },
    confirmupdateend(){
      if(this.exceed_date.length>0){
        updateendConsumers({ ids: this.selects,exceed_date:this.exceed_date }).then(res=>{
          this.getList()
          this.dateVisible = false
          this.$message.success('成功')
        }).catch(e=>{
          this.dateVisible = false
        })
      }
    }
  },
};
</script>
