<template>
  <div class="box-center">
    <!-- 头 -->
    <div class="app-top">
      <div class="app-titel" style="margin-top: 10px">
        <!-- <div v-if="orgType != 0" class="div-lab">
          <div class="label">服务到期：</div>
          <div class="toptimeqhuan">
            <div
              :class="{ tophove: searchForm.residueTime == 7 }"
              @click="tabtimetap(7)"
            >
              7天内
            </div>
            <div
              :class="{ tophove: searchForm.residueTime == 15 }"
              @click="tabtimetap(15)"
            >
              15天内
            </div>
            <div
              :class="{ tophove: searchForm.residueTime == 30 }"
              @click="tabtimetap(30)"
            >
              30天内
            </div>
          </div>
        </div>
        <div v-if="orgType == 0" class="div-lab">
          <div class="label">合同结束日期：</div>
          <el-date-picker
            v-model="starTime"
            class="div-inp"
            @change="timeChange1"
            type="daterange"
            range-separator="-"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div> -->

        <div class="div-lab">
          <!-- <div class="label">合同结束日期：</div> -->
          <div class="label" style="min-width: 80px">
            <el-select
              v-model="searchForm.timeType"
              placeholder="请选择"
              style="width: 100px"
            >
              <el-option
                v-for="item in timeTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <el-date-picker
            v-model="starTime"
            class="div-inp"
            @change="timeChange1"
            style="width: 250px"
            type="daterange"
            range-separator="-"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>

        <div v-if="orgType == 0" class="div-lab">
          <div class="label">项目类型：</div>
          <el-select
            v-model="searchForm.houseType"
            placeholder="请选择"
            class="div-inp"
            filterable
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="div-lab">
          <div class="label">服务状态：</div>
          <el-select
            v-model="searchForm.serviceStatus"
            placeholder="请选择"
            class="div-inp"
            filterable
            clearable
          >
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="div-lab">
          <div class="label">地区：</div>
          <!-- <el-select
            v-model="searchForm.provinceId"
            placeholder="请选择"
            class="div-inp"
            filterable
            clearable
          >
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select> -->
          <el-cascader
            :props="props1"
            @change="locationsChange1"
            :options="addressOptions"
            placeholder="省/市"
            size="small"
            separator="/"
            v-model="area"
            filterable
            clearable
          ></el-cascader>
        </div>
        <div v-if="orgType == 0 || orgType == 1" class="div-lab">
          <div class="label">运营人员：</div>
          <!-- <el-input
            v-model="searchForm.operationalPeople"
            maxlength="8"
            clearable
            class="div-inp"
            placeholder="请输入内容"
          ></el-input> -->
          <el-select
            v-model="searchForm.operationStaffId"
            placeholder="请选择"
            class="div-inp"
            filterable
            clearable
          >
            <el-option
              v-for="item in operaList"
              :key="item.accountId"
              :label="item.name"
              :value="item.accountId"
            >
            </el-option>
          </el-select>
        </div>
        <div v-if="orgType == 0" class="div-lab">
          <div class="label">代理商名称：</div>

          <el-input
            class="div-inp"
            maxlength="30"
            clearable
            v-model="searchForm.agentName"
            placeholder="请输入内容"
          ></el-input>
        </div>

        <div v-if="orgType != 2" class="div-lab">
          <div class="label">公司名称：</div>
          <el-input
            class="div-inp"
            v-model="searchForm.corporateName"
            placeholder="请输入内容"
            maxlength="30"
            clearable
          ></el-input>
        </div>

        <div class="div-lab">
          <div class="label">项目名称：</div>
          <el-select
            class="div-inp"
            v-model="searchForm.propertyName"
            filterable
            clearable
            @change="houseChange"
            placeholder="请选择项目"
          >
            <el-option
              v-for="item in houseList"
              :key="item.id"
              :label="item.propertyName"
              :value="item.propertyName"
            >
            </el-option>
          </el-select>
          <!-- <el-input
            class="div-inp"
            v-model="searchForm.propertyName"
            placeholder="请输入内容"
            maxlength="30"
            clearable
          ></el-input> -->
        </div>
      </div>
      <!-- <div class="app-titel" style="margin-top: 10px">

      </div> -->
      <div class="app-titel" style="margin-top: 10px">
        <div class="label" style="color: #ffffff">筛选相关：</div>
        <div style="margin-left: 5px">
          <el-button @click="screen" type="primary">筛选</el-button>
        </div>
        <div style="margin-left: 20px">
          <el-button @click="empty">清空筛选条件</el-button>
        </div>
        <div style="margin-left: auto; margin-right: 20px" v-if="orgType != 2">
          <el-button v-if="cus_build_index_add" type="primary" @click="addHouse"
            >新增</el-button
          >
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="cen-tab">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column
          prop="propertyName"
          :show-overflow-tooltip="true"
          width="120px"
          label="项目名称"
          align="center"
        >
        </el-table-column>

        <el-table-column
          :show-overflow-tooltip="true"
          width="120px"
          prop="agentName"
          label="代理商"
          align="center"
          v-if="orgType == 0"
        >
          <template slot-scope="{ row }">
            {{ row.agentName || "-" }}
          </template>
        </el-table-column>

        <el-table-column
          :show-overflow-tooltip="true"
          width="120px"
          prop="corporateName"
          label="公司"
          align="center"
          v-if="orgType != 2"
        >
        </el-table-column>

        <el-table-column
          :show-overflow-tooltip="true"
          width="120px"
          prop="provinceName,cityName"
          label="项目地区"
          align="center"
          :key="Math.random()"
        >
          <template slot-scope="scope">
            {{ scope.row.provinceName }}{{ scope.row.cityName }}
          </template>
        </el-table-column>

        <el-table-column
          width="110px"
          prop="linkman"
          label="联系人信息"
          align="center"
          :key="Math.random()"
        >
          <template slot-scope="{ row }">
            {{ row.linkman + "-" + row.linkmanPhone || "-" }}
          </template>
        </el-table-column>

        <el-table-column
          :key="Math.random()"
          width="100"
          prop="managerPhone"
          label="管理员账号"
          align="center"
        >
          <template slot-scope="{ row }">
            {{ row.managerPhone || "-" }}
          </template>
        </el-table-column>

        <el-table-column
          :key="Math.random()"
          prop="operationStaffName"
          v-if="orgType == 0 || orgType == 1"
          label="运营人员"
          align="center"
        >
        </el-table-column>

        <el-table-column
          :key="Math.random()"
          prop="houseType"
          label="项目类型"
          align="center"
          v-if="orgType != 2"
        >
          <template slot-scope="{ row }">
            {{
              row.houseType == 0
                ? "正式"
                : row.houseType == 1
                ? "试用"
                : row.houseType == 2
                ? "演示"
                : "测试"
            }}
          </template>
        </el-table-column>

        <el-table-column
          prop="startWorking"
          label="合同开始日期"
          width="100"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="endWorking"
          width="100"
          label="合同结束日期"
          align="center"
        >
        </el-table-column>

        <el-table-column label="添加日期" width="100" align="center">
          <template slot-scope="{ row }">
            {{ row.createTime.substring(0, 10) }}
          </template>
        </el-table-column>

        <el-table-column prop="residueTime" label="服务状态" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.residueTime > 0">
              服务中({{
                scope.row.residueTime * 1 >= 0
                  ? scope.row.residueTime
                  : scope.row.residueTime * -1
              }})
            </div>
            <div v-if="scope.row.residueTime <= 0">
              过期({{
                scope.row.residueTime * 1 >= 0
                  ? scope.row.residueTime
                  : scope.row.residueTime * -1
              }})
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="lockFlag" label="状态" align="center">
          <template slot-scope="{ row }">
            {{ row.lockFlag == 1 ? "禁用" : "启用" }}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              v-if="cus_build_index_edit"
              @click="edit(row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              v-if="orgType != 2 && cus_build_index_change"
              @click="changeAccount(row)"
              >更换账号</el-button
            >
            <el-button
              type="text"
              size="small"
              v-if="cus_build_index_sys"
              @click="editOpera(row, 0)"
              >系统运营</el-button
            >
            <el-button
              type="text"
              size="small"
              v-if="cus_build_index_agent"
              @click="editOpera(row, 1)"
              >售后运营</el-button
            >
            <el-button
              type="text"
              size="small"
              v-if="cus_build_index_bindAgent"
              @click="bindAgent(row)"
              >绑定代理商</el-button
            >
            <el-button type="text" v-if="cus_build_index_del" @click="del(row)"
              >删除</el-button
            >
            <el-button
              type="text"
              v-if="cus_build_index_open"
              size="small"
              @click="toDisable(row)"
              >{{ row.lockFlag == 0 ? "禁用" : "启用" }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 30, 50]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      :title="editFlag ? '编辑项目' : '新增项目'"
      :visible.sync="dialogVisible"
      @close="dialogClose"
    >
      <el-form
        :model="ruleForm"
        label-position="labelPosition"
        ref="ruleForm"
        label-width="150px"
        style="width: 60%"
        :rules="rules"
      >
        <el-form-item label="公司" prop="orgCode" v-if="orgType != 2">
          <el-select
            :disabled="editFlag == true"
            v-model="ruleForm.orgCode"
            filterable
            placeholder="请选择公司"
          >
            <el-option
              v-for="item in orgList"
              :key="item.id"
              :label="item.name"
              :value="item.orgCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目类型" prop="houseType" v-if="orgType != 2">
          <el-radio-group v-model="ruleForm.houseType" style="width: 400px">
            <el-radio :label="0">正式</el-radio>
            <el-radio :label="1">试用</el-radio>
            <el-radio :label="2">演示</el-radio>
            <el-radio :label="3">测试</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="项目名称" prop="propertyName">
          <el-input
            v-model="ruleForm.propertyName"
            maxlength="30"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="合同起止日期"
          prop="startWorking"
          v-if="orgType != 2"
        >
          <el-date-picker
            v-model="time"
            @change="timeChange"
            type="daterange"
            range-separator="-"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系人" prop="linkman">
          <el-input
            v-model="ruleForm.linkman"
            maxlength="20"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="联系手机" prop="linkmanPhone">
          <el-input
            v-model="ruleForm.linkmanPhone"
            type="tel"
            maxlength="11"
            onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)));"
          ></el-input>
        </el-form-item>
        <el-form-item label="项目地区" prop="provinceId">
          <el-cascader
            :props="props"
            @change="locationsChange"
            :options="addressOptions"
            placeholder="省/市"
            size="small"
            separator="/"
            v-model="ruleForm.area"
            filterable
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="ruleForm.address"
            type="textarea"
            maxlength="60"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="管理员账号" prop="managerPhone" v-if="!editFlag">
          <el-input
            auto-complete="new-password"
            maxlength="11"
            onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)));"
            v-model="ruleForm.managerPhone"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="管理员密码"
          prop="managerPassword"
          v-if="!editFlag"
        >
          <el-input
            auto-complete="new-password"
            v-model="ruleForm.managerPassword"
            maxlength="18"
            type="passsword"
            show-password
            :disabled="passFlag"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addSurequxiao()">取 消</el-button>
        <el-button type="primary" :loading="loadingFlag" @click="addSure">
          <!-- {{
          editFlag ? "编辑" : "保存"
        }} -->
          保存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="更换账号"
      :visible.sync="changeFlag"
      @close="$refs.accountForm.resetFields()"
      width="400px"
    >
      <el-form
        :model="accountForm"
        label-width="100px"
        ref="accountForm"
        :rules="accountRules"
      >
        <el-form-item label="管理员账号:" prop="managerPhone">
          <el-input
            style="width: 200px"
            maxlength="11"
            v-model.number="accountForm.managerPhone"
            onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)));"
          ></el-input>
        </el-form-item>
        <el-form-item label="管理员密码:" prop="managerPassword">
          <el-input
            style="width: 200px"
            :disabled="passFlag"
            show-password
            v-model="accountForm.managerPassword"
          ></el-input>
        </el-form-item>
      </el-form>
      <div style="display: flex; justify-content: space-around">
        <el-button @click="changeFlag = false">取 消</el-button>
        <el-button type="primary" @click="changeSure" :loading="loadingFlag"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :title="sysFlag == 0 ? '绑定系统运营' : '绑定售后运营'"
      :visible.sync="operaVisible"
    >
      <el-form
        :model="operaForm"
        label-position="labelPosition"
        :rules="operaRules"
        ref="operaForm"
        label-width="140px"
      >
        <el-form-item label="运营人员：" prop="operationalPeople">
          <el-select
            v-model="operaForm.operationalPeople"
            filterable
            multiple
            style="width: 80%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in optionsoperationalPeople"
              :key="item.value"
              :label="item.name"
              :value="item.accountId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="operaVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loadingFlag" @click="saveOpera()"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="绑定代理商" :visible.sync="agentVisible">
      <el-form
        :model="agentForm"
        label-position="labelPosition"
        :rules="agentRule"
        ref="agentForm"
        label-width="140px"
      >
        <el-form-item label="代理商：" prop="agentId">
          <el-select
            v-model="agentForm.agentId"
            style="width: 80%"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in optionsagentId"
              :key="item.id"
              :label="item.agentName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="agentVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loadingFlag" @click="saveAgent()"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getAreaList } from "@/api/modules/api";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        // callback(new Error("请输入手机号"));
        callback();
      } else {
        if (value) {
          if (!/^1[3456789]\d{9}$/.test(value)) {
            // alert("手机号码不合法，请重新输入");
            callback(new Error("手机号格式错误，请重新输入"));
          }
        }
        callback();
      }
    };
    var validatePass1 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入管理员账号"));
      } else {
        if (value) {
          this.passFlag = false;
          if (!/^1[3456789]\d{9}$/.test(value)) {
            // alert("手机号码不合法，请重新输入");
            callback(new Error("手机号格式错误，请重新输入"));
          } else {
            // 验证电话号码
            this.$api.api.verPhone(value).then((res) => {
              // console.log(res);
              // 判断数据是否已经有了
              if (res.data) {
                // 由用户
                this.$api.api
                  .userVerify({
                    houseId: this.accountForm.id,
                    orgType: 3,
                    accountId: res.data.sysUser.accountId,
                    username: res.data.sysUser.username,
                    agentId: localStorage.getItem("agentId"),
                    orgCode: localStorage.getItem("orgCode"),
                  })
                  .then((res1) => {
                    this.resetFlag = true;
                    this.passFlag = true;
                    if (this.changeFlag) {
                      this.accountForm.managerPassword =
                        res.data.sysUser.resultPwd;
                    } else {
                      this.ruleForm.managerPassword =
                        res.data.sysUser.resultPwd;
                    }
                    callback();
                  })
                  .catch((err) => {
                    console.log(err);
                    //
                    this.resetFlag = false;
                    callback(new Error(err));
                  });
              } else {
                // 没有用户
                // console.log("没有用户");
                // callback(new Error("没有管理员账号"));
                if (this.changeFlag) {
                  this.accountForm.managerPassword = "";
                } else {
                  this.ruleForm.managerPassword = "";
                }
                this.resetFlag = true;
                this.passFlag = false;
                callback();
              }
            });
          }
        }
        callback();
      }
    };
    return {
      props: {
        lazy: true,
        // checkStrictly: true,
        async lazyLoad(node, resolve) {
          console.log(node, 123);
          const { level } = node;
          if (level == 0) {
            console.log(23);
            const { data } = await getAreaList({ parentId: 0 }); //获取省接口
            var nodes = data.map((item) => {
              return {
                value: item.id,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 1) {
            const { data } = await getAreaList({ parentId: node.data.value }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.id,
                label: item.name,
                leaf: true,
              };
            });
            resolve(nodes);
          }
        },
      },
      props1: {
        lazy: true,
        checkStrictly: true,
        expandTrigger: "hover",
        async lazyLoad(node, resolve) {
          // console.log(node, 123);
          const { level } = node;
          if (level == 0) {
            console.log(23);
            const { data } = await getAreaList({ parentId: 0 }); //获取省接口
            var nodes = data.map((item) => {
              return {
                value: item.id,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 1) {
            const { data } = await getAreaList({ parentId: node.data.value }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.id,
                label: item.name,
                leaf: true,
              };
            });
            resolve(nodes);
          } else {
            resolve();
          }
        },
      },
      area: [],
      editFlag: false,
      changeFlag: false,
      operaVisible: false,
      resetFlag: false,
      passFlag: false,
      starTime: [],
      searchForm: {
        corporateName: "",
        propertyName: "",
        provinceId: "",
        serviceStatus: "",
        houseType: "",
        timeType: "0",
        // residueTime: 7,
        startWorking: "",
        endWorking: "",
        agentName: "",
        operationalPeople: "",
        operationStaffId: "",
      },
      areaList: [],
      operaList: [],
      options1: [
        {
          value: "0",
          label: "服务中",
        },
        {
          value: "1",
          label: "已过期",
        },
      ],
      options: [
        {
          value: "0",
          label: "正式",
        },
        {
          value: "1",
          label: "试用",
        },
        {
          value: "2",
          label: "演示",
        },
        {
          value: "3",
          label: "测试",
        },
      ],
      timeTypeList: [
        {
          value: "0",
          label: "添加时间",
        },
        {
          value: "1",
          label: "合同结束日期",
        },
      ],
      currentPage: 1,
      size: 10,
      total: 10,
      value: "",
      input: "",
      sysFlag: "0",
      idx: "0",
      tableData: [],
      optionsoperationalPeople: [],
      orgType: "",
      orgList: [],
      operationList: [],
      dialogVisible: false,
      dialogVisible1: false,
      agentVisible: false,
      loadingFlag: false,
      time: [],
      addressOptions: [],
      accountForm: {
        managerPassword: "",
        managerPhone: "",
      },
      accountRules: {
        managerPhone: [
          { required: true, message: "请填写账号", trigger: "blur" },
          { validator: validatePass1, trigger: "blur" },
        ],
        managerPassword: [
          { required: true, message: "请填写密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "请输入6~18位，数字或字母组合的密码",
            trigger: "blur",
          },
        ],
      },
      houseList: [], // 项目列表
      ruleForm: {
        orgCode: "", //公司标识
        houseType: 0, //项目类型
        propertyName: "", //项目名称
        startWorking: "", //活动开始时间
        endWorking: "", //活动结束时间
        linkman: "", //联系人
        linkmanPhone: "", //联系手机
        area: [], //项目地区
        address: "", //详细地址
        operationalPeople: "", //运营人员
        managerPhone: "", //管理员账号
        managerPassword: "", //密码
        provinceId: "", //省id
        cityId: "", //市id
        agentId: localStorage.getItem("agentId"),
      },
      ruleForm1: {},
      optionsagentId: [],
      rules: {
        orgCode: [{ required: true, message: "请选择公司", trigger: "blur" }],
        propertyName: [
          { required: true, message: "请填写项目名称", trigger: "change" },
        ],
        managerPassword: [
          { required: true, message: "请填写密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "请输入6~18位，数字或字母组合的密码",
            trigger: "blur",
          },
        ],
        startWorking: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],
        managerPhone: [
          { required: true, message: "请填写账号", trigger: "change" },
          { validator: validatePass1, trigger: "blur" },
        ],
        linkmanPhone: [{ validator: validatePass, trigger: "blur" }],
        provinceId: [
          { required: true, message: "请选择省市", trigger: "change" },
        ],
      },
      operaForm: {
        operationalPeople: "",
      },
      operaRules: {
        operationalPeople: [
          { required: false, message: "请选择运营人员", trigger: "blur" },
        ],
      },
      agentRule: {
        agentId: [{ required: true, message: "请选择代理商", trigger: "blur" }],
      },
      agentForm: {
        agentId: "",
      },
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  created() {
    this.cus_build_index_add = this.permissions["cus_build_index_add"];
    this.cus_build_index_edit = this.permissions["cus_build_index_edit"];
    this.cus_build_index_change = this.permissions["cus_build_index_change"];
    this.cus_build_index_sys = this.permissions["cus_build_index_sys"];
    this.cus_build_index_agent = this.permissions["cus_build_index_agent"];
    this.cus_build_index_bindAgent =
      this.permissions["cus_build_index_bindAgent"];
    this.cus_build_index_del = this.permissions["cus_build_index_del"];
    this.cus_build_index_open = this.permissions["cus_build_index_open"];
  },
  mounted() {
    if (this.$route.query.serviceStatus) {
      this.starTime = this.$route.query.residueTime;
      this.searchForm.startWorking = this.starTime[0];
      this.searchForm.endWorking = this.starTime[1];
      this.searchForm.serviceStatus = this.$route.query.serviceStatus;
      this.searchForm.houseType = "0";
      this.searchForm.timeType = "1";
    }
    if (this.$route.query.time) {
      this.starTime = [this.$route.query.time, this.$route.query.time];
      this.searchForm.startWorking = this.starTime[0];
      this.searchForm.endWorking = this.starTime[1];
    }
    this.orgType = localStorage.getItem("orgType");
    // 获取公司列表数据
    this.getOrgList();
    // 获取运营人员
    this.getOperaList();
    // this.getAllOperationsStaff();
    // 获取地区列表
    // this.getCityList();
    // 获取列表数据
    this.zkhousePage();
    // 获取项目列表
    this.zkhousePages();
  },
  methods: {
    //切换项目
    houseChange() {
      this.currentPage = 1;
      this.zkhousePage();
    },
    //获取项目
    zkhousePages() {
      this.$api.api
        .findHouseByUser({
          orgType: localStorage.getItem("orgType"),
        })
        .then((res) => {
          this.houseList = res.data;
        });
    },
    getOperaList() {
      if (this.orgType == 1) {
        this.$api.http
          .getAllOperationsStaffByAgent({
            agentId: localStorage.getItem("agentId"),
          })
          .then((res) => {
            // console.log(1);
            this.operaList = res.data;
            // this.operaVisible = true;
          });
      } else {
        this.$api.http.getAllOperationsStaff().then((res) => {
          this.operaList = res.data;
          // this.operaVisible = true;
          // console.log(2);
        });
      }
    },
    getCityList() {
      this.$api.api.getAreaList({ parentId: 0 }).then((res) => {
        // console.log(res,'地区列表');
        this.areaList = res.data;
      });
    },
    bindAgent(row) {
      // console.log(row);
      this.findMyAgent(row);
      this.agentVisible = true;
    },
    saveAgent() {
      this.$refs.agentForm.validate((valid) => {
        if (valid) {
          this.loadingFlag = true;
          console.log(this.agentForm);
          this.$api.api
            .saveAgent({
              agentId: this.agentForm.agentId,
              id: this.agentForm.houseId,
            })
            .then((res) => {
              setTimeout(() => {
                this.loadingFlag = false;
                console.log("防重");
              }, 1);
              this.$message.success("操作成功");
              this.zkhousePage();
              this.agentVisible = false;
            })
            .catch((err) => {
              this.loadingFlag = false;
            });
        }
      });
    },
    findMyAgent(row) {
      this.$api.http.findMyAgent({ orgType: this.orgType }).then((res) => {
        console.log(res.data);
        this.optionsagentId = res.data;
        this.agentForm.orgCode = row.orgCode;
        this.agentForm.houseId = row.id;
        this.agentForm.agentId = row.agentId;
      });
    },
    saveOpera() {
      this.$refs.operaForm.validate((valid) => {
        if (valid) {
          // console.log(valid,this.operaForm);
          this.loadingFlag = true;
          this.$api.api
            .zkoperationrecordSaveHouse({
              orgType: 3,
              accountIds: this.operaForm.operationalPeople.join(","),
              orgId: this.operaForm.orgId,
              orgCode: this.operaForm.orgCode,
              operationType: this.idx == 0 ? "1" : "2",
            })
            .then((res) => {
              console.log(res);
              setTimeout(() => {
                this.loadingFlag = false;
                console.log("防重");
              }, 1);
              this.$message.success("操作成功");
              this.operaVisible = false;
              this.zkhousePage();
            })
            .catch((err) => {
              this.loadingFlag = false;
            });
        }
      });
    },
    editOpera(row, idx) {
      // console.log(row,idx);
      // 获取运营人员列表
      this.operaForm.orgId = row.id;
      this.operaForm.orgCode = row.orgCode;
      this.sysFlag = idx;
      this.idx = idx;
      this.AllOperationsStaff(idx, row);
      this.zkoperationrecordFindByOrg(row.id, idx, row.agentId);
    },
    zkoperationrecordFindByOrg(orgId, idx, agentId) {
      this.$api.api
        .zkoperationrecordFindByOrg({
          orgType: 3,
          orgId,
          agentId,
          operationType: this.idx == 0 ? "1" : "2",
        })
        .then((res) => {
          // console.log(res);
          if (res.data.length == 0) {
            // 没有运营人员
            this.operaForm.operationalPeople = [];
          } else {
            let arr = [];
            // 有运营
            res.data.map((item) => {
              arr.push(item.accountId);
            });
            this.operaForm.operationalPeople = arr;
          }
        });
    },
    //获取运营人员
    AllOperationsStaff(idx, row) {
      console.log(idx);
      this.optionsoperationalPeople = [];
      if (idx == 1) {
        this.$api.http
          .getAllOperationsStaffByAgent({
            agentId: row.agentId,
          })
          .then((res) => {
            this.optionsoperationalPeople = res.data;
            this.operaVisible = true;
          });
      } else {
        this.$api.http.getAllOperationsStaff().then((res) => {
          this.optionsoperationalPeople = res.data;
          this.operaVisible = true;
        });
      }

      // this.$api.api.getAllOperationsStaffByAgent({agentId}).then((res) => {
      //   this.optionsoperationalPeople = res.data;
      // });
    },
    screen() {
      this.currentPage = 1;
      this.zkhousePage();
    },
    addSurequxiao() {
      this.dialogVisible = false;
    },
    // 添加项目
    addSure() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!this.resetFlag) {
            return;
          }
          this.loadingFlag = true;
          // 编辑
          if (this.editFlag) {
            this.$api.api
              .editZkhouse(this.ruleForm)
              .then((res) => {
                console.log(res);
                if (res.code == 0) {
                  this.dialogVisible = false;
                  setTimeout(() => {
                    this.loadingFlag = false;
                    console.log("防重");
                  }, 1);
                  this.$message.success("编辑成功");
                  this.zkhousePage();
                }
              })
              .catch((err) => {
                this.loadingFlag = false;
              });
          } else {
            // 添加
            this.$api.api
              .addZkhouse(this.ruleForm)
              .then((res) => {
                console.log(res);
                if (res.code == 0) {
                  this.dialogVisible = false;
                  setTimeout(() => {
                    this.loadingFlag = false;
                    console.log("防重");
                  }, 1);
                  this.$message.success("新增项目成功");
                  this.zkhousePage();
                }
              })
              .catch((err) => {
                this.loadingFlag = false;
              });
          }
        }
      });
    },
    toDisable(row) {
      this.$confirm(
        `确定${
          row.lockFlag == 0
            ? "禁用" + "-" + row.propertyName + "-"
            : "启用" + "-" + row.propertyName + "-"
        }项目吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // return
          // console.log(123);
          this.$api.api
            .editZkhouse({ id: row.id, lockFlag: row.lockFlag == 0 ? 1 : 0 })
            .then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                this.zkhousePage();
              } else {
                this.$message.error(res.message);
              }
            });
        })
        .catch((err) => {
          // console.log('关闭');
          // console.log(err);
        });
    },
    dialogClose() {
      this.restFrom();
    },
    restFrom() {
      this.$refs.ruleForm.resetFields();
      this.time = [];
      this.ruleForm = {
        orgCode: "", //公司标识
        houseType: 0, //项目类型
        propertyName: "", //项目名称
        startWorking: "", //活动开始时间
        endWorking: "", //活动结束时间
        linkman: "", //联系人
        linkmanPhone: "", //联系手机
        area: [], //项目地区
        address: "", //详细地址
        operationalPeople: "", //运营人员
        managerPhone: "", //管理员账号
        managerPassword: "", //密码
        provinceId: "", //省id
        cityId: "", //市id
      };
    },
    // 新增项目,弹框显示
    addHouse() {
      this.editFlag = false;
      this.dialogVisible = true;
      this.passFlag = false;
    },
    edit(row) {
      console.log(row);
      this.resetFlag = true;
      this.time = [
        row.startWorking.substring(0, 10),
        row.endWorking.substring(0, 10),
      ];
      // console.log(this.time)
      this.ruleForm = Object.assign({}, row);
      this.ruleForm.area = [this.ruleForm.provinceId, this.ruleForm.cityId];
      this.dialogVisible = true;
      // 获取地区选择数据,在这里对回显的时候进行操作，首先先获取一级省的数据
      // this.getProvinceList();
      // 级联选择器回显问题

      this.editFlag = true;
    },
    // 更换账号
    changeAccount(row) {
      this.changeFlag = true;
      this.passFlag = false;
      this.accountForm.id = row.id;
    },
    changeSure() {
      if (!this.resetFlag) {
        this.$message.error("平台用户与项目用户不能重复添加！");
        return;
      }
      this.$refs.accountForm
        .validate((valid) => {
          if (valid) {
            this.loadingFlag = true;
            this.$api.api.updateManagerPhone(this.accountForm).then((res) => {
              if (res.code == 0) {
                this.changeFlag = false;
                setTimeout(() => {
                  this.loadingFlag = false;
                }, 1);
                this.$message.success("编辑成功");
                this.zkhousePage();
              }
            });
          }
        })
        .catch((err) => {
          this.loadingFlag = false;
        });
    },
    del(row) {
      console.log(row, "删除");
      this.$confirm(`是否删除此项目?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true,
        type: "warning",
      }).then(() => {
        axios({
          url: `/autoSR/zkhouse/${row.id}`,
          method: "delete",
          // params: {
          //   id: row.id,
          // },
        }).then((res) => {
          if (res.code == 0) {
            this.$message.success("删除成功");
            this.zkhousePage();
          } else {
            this.$message.warning(res.resMsg);
          }
        });
      });
    },
    // 时间改变
    timeChange(e) {
      console.log(e);
      this.ruleForm.startWorking = e[0];
      this.ruleForm.endWorking = e[1];
    },
    // 获取公司列表
    getOrgList() {
      this.$api.api
        .getCompanyList({
          orgType: this.orgType,
          agentId: localStorage.getItem("agentId"),
        })
        .then((res) => {
          if (res.code == 0) {
            this.orgList = res.data;
          }
        });
    },
    // 获取运营人员地址
    getAllOperationsStaff() {
      this.$api.api.getAllOperationsStaff().then((res) => {
        console.log(res);
        if (res.code == 0) {
          this.operationList = res.data;
        }
      });
    },
    // 获取项目列表
    zkhousePage() {
      let obj = {
        current: this.currentPage,
        size: this.size,
        orgType: localStorage.getItem("orgType"),
        agentId: localStorage.getItem("agentId"),
        orgCode: localStorage.getItem("orgCode"),
        operationType:
          localStorage.getItem("orgType") == 0
            ? "1"
            : localStorage.getItem("orgType") == 1
            ? "2"
            : "",
        ...this.searchForm,
      };
      if (this.orgType == 0) {
        obj.residueTime = null;
      }
      this.$api.api.zkhousePage(obj).then((res) => {
        // console.log(res)
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },
    async getProvinceList(parentId = 0) {
      let _this = this;
      this.addressOptions = [];
      let res = await getAreaList({ parentId });
      // console.log(res);
      // 当他没有值时给addressOptions赋值，这是第一个数组
      if (res.code == 0) {
        // _this.$set(_this, 'addressOptions',_this.ruleForm.cityIds&&_this.ruleForm.provinceId ? this.loadOptions(res.data||[] ):res.data)
        let arr = [];
        res.data.map((item) => {
          let obj = {};
          obj.value = item.id;
          obj.label = item.name;
          obj.leaf = false;
          obj.children = [];
          arr.push(obj);
        });
        this.addressOptions = arr;
        this.loadOptions();
      }
    },
    loadOptions() {
      // console.log(this.addressOptions);
      this.addressOptions.map((item, idx) => {
        if (item.value == this.ruleForm.provinceId) {
          console.log("有匹配项");
          getAreaList({ parentId: this.ruleForm.provinceId }).then((res) => {
            if (res.code == 0) {
              let arr = [];
              res.data.map((item1) => {
                let obj = {};
                obj.value = item1.id;
                obj.label = item1.name;
                obj.leaf = true;
                arr.push(obj);
              });
              this.$set(this.addressOptions[idx], "children", arr);
              // console.log(this.addressOptions[idx], "123");
              this.addressOptions = Object.assign([], this.addressOptions);
              this.area = null;
              setTimeout(() => {
                this.ruleForm.area = [
                  this.ruleForm.provinceId,
                  this.ruleForm.cityId,
                ];
                // console.log(1);
                // console.log(this.addressOptions);
                // console.log(this.area);
                this.$forceUpdate();
              }, 50);
            }
          });
        }
        this.dialogVisible = true;
      });
    },
    empty() {
      this.starTime = [];
      this.searchForm = {
        corporateName: "",
        propertyName: "",
        serviceStatus: "",
        provinceId: "",
        houseType: "",
        timeType: "0",
        // residueTime: 7,
        startWorking: "",
        endWorking: "",
        agentName: "",
        operationalPeople: "",
        operationStaffId: "",
      };
      this.area = [];
      this.currentPage = 1;
      this.zkhousePage();
    },
    timeChange1(e) {
      if (e) {
        this.searchForm.startWorking = e[0];
        this.searchForm.endWorking = e[1];
      } else {
        this.searchForm.startWorking = "";
        this.searchForm.endWorking = "";
      }
    },
    tabtimetap(idx) {
      this.searchForm.residueTime = idx;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.zkhousePage();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.zkhousePage();
    },
    locationsChange(e) {
      console.log(e);
      if (!e) return;
      this.ruleForm.provinceId = e[0];
      this.ruleForm.cityId = e[1];
    },
    locationsChange1(e) {
      console.log(e);
      if (!e) return;
      this.searchForm.provinceId = e[0];
      this.searchForm.cityId = e[1];
    },
  },
};
</script>

<style scoped="scoped" lang="scss" >
.box-center {
  width: 100%;
  padding: 15px;
  min-width: 1000px;
  padding-bottom: 100px;
}
.cen-tab {
  width: 100%;
  padding: 15px;
  background: #ffffff;
  margin-top: 15px;
}
.tophove {
  color: #ffffff;
  background: #2671e2;
}
.app-top {
  width: 100%;
  background: #ffffff;
  box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.04);
  border-radius: 4px;
  padding-top: 15px;
  padding-bottom: 15px;
  .app-titel {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .label {
      font-size: 14px;
      font-weight: 400;
      color: #32363d;
      line-height: 32px;
      margin-left: 15px;
      min-width: 100px;
      text-align: right;
    }
    .toptimeqhuan {
      height: 30px;
      background: #ffffff;
      display: flex;
      align-items: center;
    }
    .toptimeqhuan div {
      padding-left: 20px;
      padding-right: 20px;
      text-align: center;
      line-height: 30px;
      font-size: 14px;
      margin-right: 15px;
      border-radius: 4px;
      border: 1px solid #e0e0e0;
    }
  }
}
.div-lab {
  display: flex;
  margin: 5px;
}
.div-inp {
  width: 250px;
}
</style>
