<template>
  <div class="app-container">
    <div>
      <el-select
        v-model="listQuery.company"
        placeholder="所属单位"
        clearable
        style="width: 200px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in companyData"
          :key="item.key"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <!-- <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="search"
        placeholder="姓名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</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="uploadUrl"
  :on-success="handleUploadSuccess"
  accept=".xlsx"
  :headers="myHeaders"
  :show-file-list ="false"
  >
  <el-button size="small" type="primary" @click="popovervisible = false">上传导入</el-button>
</el-upload>
  </div>
  <el-button slot="reference">Excel导入</el-button>
</el-popover>
    </div>
    <el-table
      :data="consumerList"
      style="width: 100%;margin-top:10px;"
      border
      fit
      v-loading="listLoading"
      highlight-current-row
      max-height="600"
    >
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column align="center" label="姓名">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="手机号">
        <template slot-scope="scope">{{ scope.row.username }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="小程序OpenId">
        <template slot-scope="scope">{{ scope.row.openid }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="微信昵称">
        <template slot-scope="scope">{{ scope.row.nickname }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="单位">
        <template
          slot-scope="scope"
          v-if="scope.row.company_name != null"
        >{{ scope.row.company_name }}</template>
      </el-table-column>
      <el-table-column align="center" label="缴费学科">
        <template slot-scope="scope" >
          <el-tag
    v-for="item in scope.row.subjects_name"
    :key="item">
    {{ item }}
  </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" 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="创建日期">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope)"
            icon="el-icon-edit"
            :disabled="!checkPermission(['consumer_update'])"
            v-if="!scope.row.is_superconsumer"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope)"
            icon="el-icon-delete"
            :disabled="!checkPermission(['consumer_delete'])"
            v-if="!scope.row.is_superconsumer"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <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-select v-model="consumer.company" placeholder="单位" style="width:100%">
    <el-option
      v-for="item in companyData"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      >
    </el-option>
  </el-select>
  </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="subjects">
      <el-select v-model="consumer.workscope" placeholder="工作类别" style="width:100%" >
    <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>
      <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>
  </div>
</template>

<script>
import {
  getConsumerList,
  createConsumer,
  deleteConsumer,
  updateConsumer,
  importConsumer
} 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 { uploadUrl } from "@/api/file";
import { getToken } from "@/utils/auth";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

const defaultConsumer = {
  id: "",
  name: "",
  username: "",
  company: null,
  subjects:[],
  workscope:null
};
const listQuery = {
  page: 1,
  limit: 20
};
export default {
  components: { Pagination },
  watch: {
    filterOrgText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      uploadUrl: uploadUrl(),
      popovervisible: false,
      consumer: defaultConsumer,
      myHeaders: { Authorization: "JWT " + getToken() },
      consumerList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      search: "",
      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" }]
        // password: [
        //   { required: true, message: "请输入密码", trigger: "change" }
        // ],
      },
      filterOrgText: "",
      treeLoding: false,
      companyData: [],
      subjectData: [],
      workscopeData:[],
    };
  },
  computed: {},
  created() {
    this.getList();
    this.getCompanyList();
    this.getSubjectAll();
    this.getWorkScopeAll();
  },
  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(query = this.listQuery) {
      this.listLoading = true;
      getConsumerList(query).then(response => {
        this.consumerList = response.data.results;
        this.total = response.data.count;
        this.listLoading = false;
      });
    },
    getCompanyList() {
      this.treeLoding = true;
      getCompanyList().then(response => {
        this.companyData = genTree(response.data);
        this.treeLoding = false;
      });
    },
    getSubjectAll() {
      getSubjectAll().then(response => {
        this.subjectData = genTree(response.data);
      });
    },
    getWorkScopeAll() {
      getWorkScopeAll().then(response => {
        this.workscopeData = genTree(response.data);
      });
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        limit: 20
      };
      this.getList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSearch() {
      this.getList({ search: this.search });
    },
    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
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["consumerForm"].clearValidate();
      });
    },
    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);
        });
    },
    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(() => {
              // 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.$notify({
                title: "成功",
                message: "编辑成功",
                type: "success",
                duration: 2000
              });
            });
          } else {
            createConsumer(this.consumer).then(res => {
              // this.consumer = res.data
              // this.consumerList.unshift(this.consumer)
              this.getList();
              this.dialogVisible = false;
              this.$notify({
                title: "成功",
                message: "新增成功",
                type: "success",
                duration: 2000
              });
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
