<template>
  <div class="app-container">
        <div style="margin-top:10px">
          <el-input
            v-model="listQuery.search"
            placeholder="输入部门名称进行搜索"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus" v-if ="checkPermission(['company_create'])">新增</el-button>
                <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-refresh-left"
        @click="resetFilter"
      >刷新重置</el-button>
      <el-button
        type="primary"
        @click="handleTrans"
        v-if="checkPermission(['consumer__transfers'])"
      >批量移交</el-button>
        </div>
        
        <el-table
          :data="tableData.results"
          style="width: 100%;margin-top:10px;"
          border
          fit
          v-loading="listLoading"
          highlight-current-row
          max-height="600"
          row-key="id"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="单位名称">
            <template slot-scope="scope">{{ scope.row.name }}</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 label="所属">
            <template slot-scope="scope">
              <span>{{ scope.row.create_admin_name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope)"
                icon="el-icon-edit"
                :disabled="!checkPermission(['company_update'])"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope)"
                icon="el-icon-delete"
                :disabled="!checkPermission(['company_delete'])"
              ></el-button>
              <el-button 
              v-if="checkPermission(['company_transfer'])"
              type="primary" 
              size="small"
              @click="transfer(scope)"
              >移交</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
    <pagination
      v-show="tableData.count>0"
      :total="tableData.count"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑单位':'新增单位'" >
      <el-form :model="company" label-width="80px" label-position="right" :rules="rule1" ref="companyForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="company.name" 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="confirmCompany('companyForm')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCompanyList, createCompany, deleteCompany, updateCompany, transferCompany, transferCompanys } from "@/api/crm";
import { deepClone } from "@/utils";
import checkPermission from "@/utils/permission";
import Pagination from "@/components/Pagination"



const defaultCompany = {
        id: "",
        name: "",
      };
const listQuery = {
  page: 1,
  limit: 20,
  search: ""
}
export default {
  components: { Pagination },
  data() {
    return {
      selects:[],
      company: {
        id: "",
        name: "",
      },
      listQuery:listQuery,
      tableData: {count:0},
      listLoading: true,
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        // pid: [{ required: true, message: "请选择上级", trigger: "change" }]
        // password: [
        //   { required: true, message: "请输入密码", trigger: "change" }
        // ],
      },
    };
  },
  computed: {},
  created() {
    this.getList();
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true
      getCompanyList(this.listQuery).then(response => {
        this.tableData = response.data
        this.listLoading = false
      });
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        limit: 20,
        search: ""
      };
      this.getList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleAdd() {
      this.company = Object.assign({}, defaultCompany);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["companyForm"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.company = Object.assign({}, scope.row); // copy obj
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["companyForm"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除该单位吗?将丢失数据!", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error"
      })
        .then(async () => {
          await deleteCompany(scope.row.id);
          this.getList()
          this.$message({
            type: "success",
            message: "成功删除!"
          });
        })
        .catch(err => {
          // console.error(err);
        });
    },
    async confirmCompany(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            updateCompany(this.company.id, this.company).then(() => {
              this.getList();
              this.dialogVisible = false;
              this.$notify({
                title: "成功",
                message: "编辑成功",
                type: "success",
                duration: 2000
              });
            });
          } else {
            createCompany(this.company).then(res => {
              // this.company = res.data
              // this.tableData.unshift(this.company)
              this.getList();
              this.dialogVisible = false;
              this.$notify({
                title: "成功",
                message: "新增成功",
                type: "success",
                duration: 2000
              });
            });
          }
        } else {
          return false;
        }
      });
    },
    transfer(scope) {
        this.$prompt('请输入管理员账号以确认将('+scope.row.name + ')及其学员转交给他', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          // inputErrorMessage: '邮箱格式不正确'
        }).then(({ value }) => {
          transferCompany(scope.row.id, {'admin':value}).then(res=>{
            this.$message.success('转交成功!')
            this.getList()
          })
        }).catch(() => {      
        });
      },
      handleSelectionChange(val) {
      let selects = [];
      for (var i = 0; i < val.length; i++) {
        selects.push(val[i].id);
      }
      this.selects = selects;
    },
      handleTrans() {
      if (this.selects.length) {
        this.$prompt('请输入管理员账号以确认将'+this.selects.length + '家企业及其学员转交给他', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          // inputErrorMessage: '邮箱格式不正确'
        }).then(({ value }) => {
          transferCompanys({admin:value, companys:this.selects}).then(res=>{
            this.$message.success('转交成功!')
            this.getList()
          })
        }).catch(() => {      
        });
      } else {
        this.$message({
          message: "请先选择",
          type: "warning",
        });
      }
      }
  }
};
</script>
