<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select v-model="listQuery.cityId" clearable class="filter-item" placeholder="请选择归属城市" @change="citySelectChange" filterable>
        <el-option v-for="item in citys" :key="item.id" :label="item.cityName" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.stationId" clearable class="filter-item" placeholder="请选择服务站" multiple="" filterable>
        <el-option v-for="item in citySelectStations" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="请输入手机号码" />
      <el-button v-permission="['GET /admin/servant/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/servant/create']" class="filter-item" type="primary" icon="el-icon-search" @click="handleJoinBtn">添加</el-button>
      <!-- <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="城市" prop="cityId">
        <template slot-scope="scope">
          <el-tag>{{ cityFilter(scope.row.cityId)}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="服务站" prop="stationName" />
      <el-table-column align="center" label="姓名" prop="name" />
      <el-table-column align="center" label="手机" prop="mobile" />
      <el-table-column align="center" label="备用手机" prop="mobile2" />
      <el-table-column align="center" label="类型" prop="type">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.type | TypeFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="最近登录时间" prop="lastLoginTime" />
      <el-table-column align="center" label="加入时间" prop="createTime" />
      <el-table-column align="center" label="状态" prop="deleted">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleted?'success':''">{{  scope.row.deleted?'停用':'可用'}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/servant/update']" type="text" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-permission="['GET /admin/servant/delete']" style="color:red" v-if="scope.row.deleted==false" type="text" icon="el-icon-close" size="mini" @click="handleDelete(scope.row)">停用</el-button>
          <el-button v-permission="['GET /admin/servant/usable']"  v-if="scope.row.deleted==null||scope.row.deleted" type="text" icon="el-icon-check" size="mini" @click="handleUsable(scope.row)">启用</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="joinDialogVisible" title="加入申请" width="600px">

      <el-form ref="dataJoinForm" :rules="passRules" :model="dataJoinForm" status-icon label-position="left" label-width="150px" style="width:300px; margin-left:50px;">

        <el-form-item label="使用者姓名" prop="name">
          <el-input v-model="dataJoinForm.name" style="width:300px" />
        </el-form-item>

        <el-form-item label="使用者手机" prop="mobile">
          <el-input :disabled="dataJoinForm.disabled" v-model="dataJoinForm.mobile" style="width:300px" oninput="if(value.length > 11) value = value.slice(0, 11)" />
        </el-form-item>

        <el-form-item label="备用手机" prop="mobile">
          <el-input   v-model="dataJoinForm.mobile2" style="width:300px" oninput="if(value.length > 11) value = value.slice(0, 11)" />
        </el-form-item>

        <el-form-item label="选择归属城市" prop="cityId">
          <el-select v-model="dataJoinForm.cityId" clearable class="filter-item" placeholder="请选择归属城市" @change="cityChange" filterable>
            <el-option v-for="item in citys" :key="item.id" :label="item.cityName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="服务站" prop="stationId">
          <el-select v-model="dataJoinForm.stationId" clearable class="filter-item" placeholder="请选择服务站" filterable>
            <el-option v-for="item in cityStations" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="使用者类型" prop="type">
          <el-select v-model="dataJoinForm.type" clearable class="filter-item" placeholder="请选择使用者类型">
            <el-option label="阿姨小哥" :value="1" />
            <el-option label="站长" :value="2" />
            <el-option label="其他" :value="98" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="deleted">
          <el-select v-model="dataJoinForm.deleted" clearable class="filter-item" placeholder="请选择状态">
            <el-option label="可用" :value="false" />
            <el-option label="停用" :value="true" />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="joinDialogVisible = false">取消</el-button>
        <el-button v-if="dataJoinForm.id==0" type="primary" @click="handleCreate()">确定</el-button>
        <el-button v-else type="primary" @click="handleUpdate()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { list, create, update, deleteServant } from "@/api/servant";
import BackToTop from "@/components/BackToTop";
import { listAllCity } from "@/api/city";
import { stations } from "@/api/enumUtils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

export default {
  name: "servant",
  components: { BackToTop, Pagination },
  filters: {
    TypeFilter(type) {
      if (type == null || type == 0) return "小家政合伙人";
      if (type == 1) return "阿姨小哥";
      if (type == 2) return "站长";
      if (type == 3) return "大客户";
      if (type == 4) return "公司员工";
      if (type == 5) return "公司BD";
      if (type == 6) return "引荐人";
      if (type == 99) return "临时工";
      return "";
    },
  },
  data() {
    return {
      stations: stations,
      citySelectStations: [],
      cityStations: [],
      list: [],
      total: 0,
      citys: [],
      listLoading: true,
      dataForm: {},
      listQuery: {
        page: 1,
        limit: 20,
        stationId: [],
        mobile: undefined,
        sort: "id",
        order: "desc",
      },
      dataJoinForm: {
        mobile: "",
        type: 1,
      },
      joinDialogVisible: false,
      downloadLoading: false,
      passRules: {
        type: [
          {
            required: true,
            message: "类型不能为空",
            trigger: "blur",
          },
        ],
        stationId: [
          {
            required: true,
            message: "请选择服务站",
            trigger: "blur",
          },
        ],
        cityId: [
          {
            required: true,
            message: "归属城市不能为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "手机不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    listAllCity().then((res) => {
      this.citys = res.data.data;
    });
  },
  methods: {
    getList() {
      this.listLoading = true;
      list(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    cityChange(value) {
      //this.dataJoinForm.stationId = "";
      let cityName = this.cityFilter(value);

      if (cityName == null) this.cityStations = [];

      let stations = [];
      this.stations.forEach((s) => {
        if (cityName.indexOf(s.city) >= 0) stations.push(s);
      });
      this.cityStations = stations;
    },
    citySelectChange(value) {
      let cityName = this.cityFilter(value);
      if (cityName == null) this.citySelectStations = [];
      let stations = [];
      this.stations.forEach((s) => {
        if (cityName.indexOf(s.city) >= 0) stations.push(s);
      });
      this.citySelectStations = stations;
    },
    cityFilter(cityId) {
      let cityName = null;
      this.citys.forEach((item) => {
        if (item.id == cityId) {
          cityName = item.cityName;
        }
      });
      return cityName;
    },
    handleEdit(row) {
      this.joinDialogVisible = true;
      this.dataJoinForm = JSON.parse(JSON.stringify(row));
      this.cityChange(this.dataJoinForm.cityId);
      this.dataJoinForm.disabled = true;
    },
    handleDelete(row) {
      this.$confirm("确定要删除【" + row.name + "】服务者吗？").then((res) => {
        deleteServant({ id: row.id }).then((res) => {
          this.$notify.success({
            title: "成功",
            message: "停用成功",
          });
          this.getList();
        });
      });
    },
    handleUsable(row) {
      this.$confirm("确定要启用【" + row.name + "】服务者吗？").then((res) => {
        usableServant({ id: row.id }).then((res) => {
          this.$notify.success({
            title: "成功",
            message: "启用成功",
          });
          this.getList();
        });
      });
    },
    handleJoinBtn() {
      this.dataJoinForm = {
        mobile: "",
        type: 1,
        id: 0,
        disabled: false,
      };
      this.joinDialogVisible = true;
    },
    handleCreate() {
      //服务站
      let station = this.stations.filter((s) => {
        return s.id == this.dataJoinForm.stationId;
      });
      this.dataJoinForm.stationName = station[0].name;

      this.$refs["dataJoinForm"].validate((valid) => {
        if (valid) {
          create(this.dataJoinForm)
            .then((res) => {
              this.$notify.success({
                title: "成功",
                message: "添加成功",
              });
              this.joinDialogVisible = false;
              this.getList();
            })
            .catch((res) => {
              this.$notify.error({
                title: "失败",
                message: res.data.errmsg,
              });
            });
        }
      });
    },

    handleUpdate() {
      //服务站
      let station = this.stations.filter((s) => {
        return s.id == this.dataJoinForm.stationId;
      });

      this.dataJoinForm.stationName = station[0].name;

      this.$refs["dataJoinForm"].validate((valid) => {
        if (valid) {
          update(this.dataJoinForm)
            .then((res) => {
              this.$notify.success({
                title: "成功",
                message: "添加成功",
              });
              this.joinDialogVisible = false;
              this.getList();
            })
            .catch((res) => {
              this.$notify.error({
                title: "失败",
                message: res.data.errmsg,
              });
            });
        }
      });
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["合伙人", "手机号", "申请时间"];
        const filterVal = ["user.username", "applyMobile", "applyTime"];
        excel.export_json_to_excel2(tHeader, this.list, filterVal, "行星申请");
        this.downloadLoading = false;
      });
    },
  },
};
</script>

<style scoped>
.el-dialog {
  width: 650px !important;
}
.el-table th.gutter {
  display: table-cell !important;
}
.el-select--medium {
  width: 300px !important;
}
</style>
