<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 v-if="orgType == 0" class="div-lab">
          <div class="label">楼盘类型：</div>
          <el-select
            v-model="searchForm.houseType"
            placeholder="请选择"
            class="div-inp"
          >
            <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"
          >
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div v-if="orgType == 0" class="div-lab">
          <div class="label">运营人员：</div>
          <el-input
            v-model="searchForm.operationalPeople"
            class="div-inp"
            placeholder="请输入内容"
          ></el-input>
        </div>
        <div v-if="orgType == 0" class="div-lab">
          <div class="label">代理商名称：</div>

          <el-input
            class="div-inp"
            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="请输入内容"
          ></el-input>
        </div>

        <div class="div-lab">
          <div class="label">楼盘名称：</div>
          <el-input
            class="div-inp"
            v-model="searchForm.propertyName"
            placeholder="请输入内容"
          ></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>
          <el-button
            @click="zkhousePage"
            style="background: #2671e2; color: #ffffff"
            >筛选</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
            style="background: #2671e2; color: #ffffff"
            @click="addHouse"
            >新增</el-button
          >
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="cen-tab">
      <el-table
        :data="tableData"
        stripe
        height="400"
        style="width: 100%"
        border
      >
        <el-table-column prop="propertyName" label="楼盘名称" align="center">
        </el-table-column>
        <el-table-column
          prop="agentName"
          label="代理商"
          align="center"
          v-if="orgType == 0"
        >
          <template slot-scope="{ row }">
            {{ row.agentName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="corporateName"
          label="公司"
          align="center"
          v-if="orgType != 2"
        >
        </el-table-column>
        <el-table-column prop="address" label="楼盘地址" align="center">
        </el-table-column>
        <el-table-column prop="address" label="联系人信息" align="center">
          <template slot-scope="{ row }">
            {{ row.linkman || "-" }}-{{ row.linkmanPhone || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="managerPhone" label="管理员账号" align="center">
          <template slot-scope="{ row }">
            {{ row.managerPhone || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="添加日期" align="center">
        </el-table-column>
        <el-table-column
          prop="address"
          label="楼盘类型"
          align="center"
          v-if="orgType != 2"
        >
          <template slot-scope="{ row }">
            {{
              row.houseType == 0 ? "正式" : row.houseType == 1 ? "试用" : "演示"
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="startWorking"
          label="合同开始日期"
          align="center"
        >
        </el-table-column>

        <el-table-column prop="endWorking" label="合同结束日期" align="center">
        </el-table-column>
        <el-table-column prop="residueTime" label="剩余天数" align="center">
        </el-table-column>
        <el-table-column prop="address" label="服务状态" align="center">
          <template slot-scope="{ row }">
            {{ row.serviceStatus == 0 ? "在服务期内" : "已过期" }}
          </template>
        </el-table-column>
        <!--  scope -->
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template slot-scope="{ row }">
            <el-button type="text" @click="edit(row)">编辑</el-button>
            <el-button type="text" v-if="orgType != 2" @click="changeAccount(row)">更换账号</el-button>
            <el-button type="text" v-if="orgType==2">添加员工</el-button>
            <!-- <el-button type="text">添加员工</el-button> -->
            <el-button type="text" @click="del(row)">删除</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, 20, 30, 40]"
          :page-size="10"
          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 v-model="ruleForm.orgCode" 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">
            <el-radio :label="0">正式</el-radio>
            <el-radio :label="1">试用</el-radio>
            <el-radio :label="2">演示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="楼盘名称" prop="propertyName">
          <el-input v-model="ruleForm.propertyName"></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"></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"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="ruleForm.address"></el-input>
        </el-form-item>
        <el-form-item label="运营人员" prop="operationalPeople" v-if="orgType == 0">
          <el-select v-model="ruleForm.operationalPeople" placeholder="请选择运营人员">
            <el-option
              v-for="item in operationList"
              :key="item.accountId"
              :label="item.name"
              :value="item.accountId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员账号" prop="managerPhone" v-if="!editFlag">
          <el-input v-model="ruleForm.managerPhone"></el-input>
        </el-form-item>
        <el-form-item
          label="管理员密码"
          prop="managerPassword"
          v-if="!editFlag"
        >
          <el-input
            v-model="ruleForm.managerPassword"
            type="passsword"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @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"  show-password  v-model.number="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">确 定</el-button>
    </div>
</el-dialog>
    <!-- <el-dialog title="新增用户" :visible.sync="dialogVisible1">
      <el-form
        :model="ruleForm1"
        label-position="labelPosition"
        ref="ruleForm1"
        label-width="100px"
        style="width: 60%; margin: 0 auto"
      >
        <el-form-item label="用户名：" prop="areaName">
          <el-input v-model="ruleForm1.areaName"></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="areaName">
          <el-radio-group v-model="ruleForm1.resource">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="登录手机：" prop="areaName">
          <el-input v-model="ruleForm1.areaName"></el-input>
        </el-form-item>
        <el-form-item label="登录密码：" prop="areaName">
          <el-input v-model="ruleForm1.areaName"></el-input>
        </el-form-item>
        <el-form-item label="角色：" prop="areaName">
          <el-select v-model="ruleForm1.region" placeholder="请选择角色">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门：" prop="areaName">
          <el-select v-model="ruleForm1.region" placeholder="请选择部门">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary">保存</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { getAreaList } from "@/api/modules/api";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        if (value) {
          if (!/^1[3456789]\d{9}$/.test(value)) {
            // alert("手机号码不合法，请重新输入");
            callback(new Error("手机号码不合法，请重新输入"));
          }
        }
        callback();
      }
    };
    return {
      props: {
        lazy: true,
        async lazyLoad(node, resolve) {
          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);
          }
        },
      },
      editFlag: false,
      changeFlag:false,
      starTime: [],
      searchForm: {
        corporateName: "",
        propertyName: "",
        serviceStatus: "",
        houseType: "",
        residueTime: 7,
        startWorking: "",
        endWorking: "",
        agentName: "",
        operationalPeople: "",
      },
      options1: [
        {
          value: "0",
          label: "服务器内",
        },
        {
          value: "1",
          label: "已失效",
        },
      ],
      options: [
        {
          value: "0",
          label: "正式",
        },
        {
          value: "1",
          label: "试用",
        },
        {
          value: "2",
          label: "演示",
        },
      ],
      currentPage: 1,
      size: "",
      total: 10,
      value: "",
      input: "",
      tableData: [],
      orgType: "",
      orgList: [],
      operationList: [],
      dialogVisible: false,
      dialogVisible1: false,
      time: [],
      addressOptions: [],
      accountForm:{
        managerPassword:"",
        managerPhone:'',
      },
      accountRules:{
        managerPhone: [
          { validator: validatePass, trigger: "change" },
        ],
      },
      ruleForm: {
        orgCode: "", //公司标识
        houseType: 0, //楼盘类型
        propertyName: "", //楼盘名称
        startWorking: "", //活动开始时间
        endWorking: "", //活动结束时间
        linkman: "", //联系人
        linkmanPhone: "", //联系手机
        area: [], //楼盘地区
        address: "", //详细地址
        operationalPeople: "", //运营人员
        managerPhone: "", //管理员账号
        managerPassword: "", //密码
        provinceId: "", //省id
        cityId: "", //市id
      },
      ruleForm1:{},
      rules: {
        orgCode: [{ required: true, message: "请选择公司", trigger: "blur" }],
        propertyName: [
          { required: true, message: "请填写楼盘名称", trigger: "change" },
        ],
        startWorking: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],
        managerPhone: [
          { validator: validatePass, trigger: "blur" },
        ],
        linkmanPhone: [{ validator: validatePass, trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.orgType = localStorage.getItem("orgType");
    // 获取公司列表数据
    this.getOrgList();
    // 获取运营人员
    this.getAllOperationsStaff();
    // 获取列表数据
    this.zkhousePage();

  },
  methods: {
    // 添加楼盘
    addSure() {
      // console.log(this.addressOptions)
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          // 编辑
          if (this.editFlag) {
            console.log("编辑");
              this.$api.api.editZkhouse(this.ruleForm).then((res) => {
              console.log(res);
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$message.success("编辑成功");
                this.zkhousePage();
              }
            });
          } else {
            // 添加
            console.log("添加");
            this.$api.api.addZkhouse(this.ruleForm).then((res) => {
              console.log(res);
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$message.success("新增楼盘成功");
                this.zkhousePage();
              }
            });
          }
        }
      });
    },
    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;
    },
    edit(row) {
      console.log(row);
      this.time = [
        row.startWorking.substring(0, 10),
        row.endWorking.substring(0, 10),
      ];
      // console.log(this.time)
      this.ruleForm = Object.assign({},row)
       // 获取地区选择数据,在这里对回显的时候进行操作，首先先获取一级省的数据
      this.getProvinceList();
      // 级联选择器回显问题

      this.editFlag = true;
    },
    // 更换账号
    changeAccount(row){
      this.changeFlag=true
      this.accountForm.id=row.id
    },
    changeSure(){
      this.$refs.accountForm.validate((valid) => {
        if(valid){
          this.$api.api.updateManagerPhone(this.accountForm)
          .then(res=>{
              if (res.code == 0) {
                this.changeFlag = false;
                this.$message.success("编辑成功");
                this.zkhousePage();
              }
          })
        }
      })

    },
      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,
        })
        .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,
        ...this.searchForm,
      };
      if (this.orgType == 0) {
        obj.residueTime = "";
      }
      this.$api.api.zkhousePage(obj).then((res) => {
        // console.log(res)
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },
    getProvinceList(parentId = 0) {
      let _this = this;
      this.addressOptions=[]
      getAreaList({ parentId }).then((res) => {
        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)
              this.area = [this.ruleForm.provinceId, this.ruleForm.cityId];
              console.log(this.addressOptions[idx],'123');
              console.log(this.area);

              this.addressOptions=Object.assign([],this.addressOptions)
              this.$forceUpdate()

            }
          });
        }
        this.dialogVisible = true;
      });
    },
    empty() {
      this.starTime = [];
      this.searchForm = {
        corporateName: "",
        propertyName: "",
        serviceStatus: "",
        houseType: "",
        residueTime: 7,
        startWorking: "",
        endWorking: "",
        agentName: "",
        operationalPeople: "",
      };
    },
    timeChange1(e) {
      this.searchForm.startWorking = e[0];
      this.searchForm.endWorking = e[1];
    },
    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];
    },
  },
};
</script>

<style scoped="scoped" lang="scss" >
.box-center {
  width: 100%;
  padding: 15px;
  min-width: 1200px;
  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;
    }
    .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>
