<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="40"></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" v-if="scope.row.geo">
          <span v-if="scope.row.geo.pname">{{ scope.row.geo.pname }}</span>
          <span v-if="scope.row.geo.cityname"
            >/{{ scope.row.geo.cityname }}</span
          >
          <span v-if="scope.row.geo.adname">/{{ scope.row.geo.adname }}</span>
        </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"
              v-if="checkPermission(['company_update'])"
            ></el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope)"
              icon="el-icon-delete"
              v-if="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-item label="所在地" prop="regin">
          <el-cascader
            size="large"
            :options="regionData"
            @change="handleRChange"
            style="width: 100%"
            clearable
            v-model="company.geo_"
          >
               
          </el-cascader>
        </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";
import { regionData, CodeToText, TextToCode } from "element-china-area-data";

const defaultCompany = {
  id: "",
  name: "",
  geo: null,
};
const listQuery = {
  page: 1,
  limit: 20,
  search: "",
};
export default {
  components: { Pagination },
  data() {
    return {
      regionData: regionData,
      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 = deepClone(defaultCompany);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["companyForm"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.company = deepClone(scope.row); // copy obj
      this.company.geo_ = ["", "", ""];
      if (scope.row.geo) {
        if (scope.row.geo.pname) {
          this.company.geo_[0] = TextToCode[scope.row.geo.pname].code;
          if (scope.row.geo.cityname) {
            if(TextToCode[scope.row.geo.pname][scope.row.geo.cityname]){
              this.company.geo_[1] = TextToCode[scope.row.geo.pname][scope.row.geo.cityname].code;
            }else{
              this.company.geo_[1] = TextToCode[scope.row.geo.pname]['市辖区'].code;
            }
            
            if (scope.row.geo.adname) {
              if(TextToCode[scope.row.geo.pname][scope.row.geo.cityname]){
              this.company.geo_[2] = TextToCode[scope.row.geo.pname][scope.row.geo.cityname][scope.row.geo.adname].code;
            }else{
              this.company.geo_[2] = TextToCode[scope.row.geo.pname]['市辖区'][scope.row.geo.adname].code;
            }
              
            }
          }
        }
      }

      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.$message.success("成功");
            });
          } else {
            createCompany(this.company).then((res) => {
              // this.company = res.data
              // this.tableData.unshift(this.company)
              this.getList();
              this.dialogVisible = false;
              this.$message.success("成功");
            });
          }
        } 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;
    },
    handleRChange(val) {
      if (val) {
        this.company.geo = {};
        if (val[0] != "") {
          this.company.geo.pname = CodeToText[val[0]];
          if (val[1] != "") {
            this.company.geo.cityname = CodeToText[val[1]];
            if (val[2] != "") {
              this.company.geo.adname = CodeToText[val[2]];
            }
          }
        }
      }
    },
    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>
