<template>
  <div class="Region">
    <div>
      <el-row type="flex" justify="space-between">
        <el-col :span="4">
          <h1 class="headerTitle">企业设置 / 区域设置</h1>
        </el-col>
        <el-col :span="3" style="text-align:right">
          <span>
            <el-button type="primary" v-if="RegionBtn.RegionBtn23" size="mini" round plain @click="AddRegionModal">新增区域</el-button>
          </span>
        </el-col>
      </el-row>
    </div>
    <div>
      <div>
        <span>
          <el-input placeholder="请输入区域或区域主管" prefix-icon="el-icon-search" v-model="valueInput"></el-input>
        </span>
        <span>
          <el-button type="primary" plain round @click="searchInput" size="small">搜索</el-button>
          <el-button type="info" plain round @click="resetInput" size="small">重置</el-button>
        </span>
      </div>
    </div>
    <div class="totalTitle">
      <span>
        总记录条数
        <i>{{tableData.total}}</i>条
      </span>
    </div>
    <div>
      <el-table
        :data="tableData.rows"
        style="width: 100% text-align:center;"
        border
        :header-cell-style="{'background-color': '#fafafa',
    'font-weight':'800'}"
      >
        <el-table-column
          prop="areaCode"
          label="区域编号"
          min-width="80"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="provinceName"
          label="省"
          min-width="80"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="cityName"
          label="市"
          min-width="80"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="areaName"
          label="区域名称"
          min-width="80"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="区域主管"
          min-width="80"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="区域说明"
          min-width="140"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="projectNum"
          label="下辖项目数量"
          min-width="80"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="num"
          label="下辖电梯数量"
          min-width="80"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="操作" min-width="160" align="center">
          <template slot-scope="{row,$index}">
            <div>
              <el-button
                type="primary"
                plain
                round
                size="small"
                @click="projectRegion(row,$index)"
              >项目编辑</el-button>
              <el-button type="primary" v-if="RegionBtn.RegionBtn24" plain round size="small" @click="EditRegion(row,$index)">编辑</el-button>
              <el-button type="danger" v-if="RegionBtn.RegionBtn25" round plain size="small" @click="DeletRegion(row,$index)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagenation">
      <span>
        <el-pagination
          background
          layout="prev, pager, next, sizes, total, jumper"
          :total="tableData.total"
          @current-change="click"
          @size-change="handleSizeChange"
          :page-sizes="[5,15, 25, 50]"
          :page-size="pagesize"
          @prev-click="customerPrev"
          @next-click="customerNext"
        ></el-pagination>
      </span>
    </div>
    <!-- 新增区域 -->
    <el-dialog
      :title="RegionTitle"
      :visible.sync="AddRegion"
      class="addProvice"
      :before-close="EidtorClose"
    >
      <div>
        <el-form :model="AddRegionData" ref="AddRegionData" label-width="100px" :rules="AddRules">
          <el-row type="flex" justify="space-between">
            <el-col :span="9">
              <el-form-item label="区域编号:" prop="areaCode">
                <el-input v-model="AddRegionData.areaCode" placeholder="请输入区域编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="省:"
                prop="provinceCode"
                :rules="[{ required: true, type:'string', message:'省不能为空', trigger: 'change'}]"
              >
                <el-select
                  v-model="AddRegionData.provinceCode"
                  @change="ChangeProvince(AddRegionData.provinceCode)"
                  placeholder="请选择市"
                >
                  <el-option
                    v-for="item in cityDatas"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="市:"
                prop="cityCode"
                :rules="[{ required: true, type:'string', message:'市不能为空', trigger: 'change'}]"
              >
                <el-select v-model="AddRegionData.cityCode" placeholder="请选择市">
                  <el-option
                    v-for="item in shiDatas"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
                <!-- <el-select
                  v-if="!Regionstatus"
                  v-model="newRegionalDatas.cityCode"
                  value-key="id"
                  @change="ChangeCity"
                  :placeholder="AddRegionData.cityName"
                >
                  <el-option
                    v-for="item in shiDatas"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  ></el-option>
                </el-select>-->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-col :span="9">
              <el-form-item
                label="区域名称:"
                prop="areaName"
                :rules="[{ required: true, type:'string', message:'区域不能为空', trigger: 'blur'}]"
              >
                <el-input v-model="AddRegionData.areaName" placeholder="请输入区域名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item
                label="区域主管:"
                prop="userId"
                :rules="[{ required: true, type:'string', message:'区域主管不能为空', trigger: 'change'}]"
              >
                <el-select
                  v-model="AddRegionData.userId"
                  placeholder="请选择区域主管"
                  @change="ChangeNameRegion"
                >
                  <el-option
                    v-for="item in Regional"
                    :key="item.userId"
                    :label="item.name"
                    :value="item.userId"
                  ></el-option>
                </el-select>
                <!-- <el-select
                  v-if="!Regionstatus"
                  v-model="newRegionalDatas.userName"
                  :placeholder="AddRegionData.name"
                  @change="ChangeNameRegion"
                  value-key="userId"
                  :loading="loading.RegionUserLoading"
                  @focus="getRegionUser"
                >
                  <el-option
                    v-for="item in Regional"
                    :key="item.userId"
                    :label="item.name"
                    :value="item"
                ></el-option>-->
                <!-- </el-select> -->
              </el-form-item>
            </el-col>
          </el-row>
          <div>
            <el-form-item label="区域说明:" prop="remark">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="AddRegionData.remark"
              ></el-input>
            </el-form-item>
          </div>
          <div class="shuttleTable">
            <el-row type="flex" justify="start" style="height:340px">
              <el-col :span="10">
                <h3 class="SelectName">分配文员</h3>
                <div class="SelectPrompt">
                  <span>双击名字即可到右侧设置成员为区域文员</span>
                </div>
                <el-table
                  height="260px"
                  style="width:100%;"
                  empty-text="无数据"
                  class="tablePrompt"
                  :data="PromptDatas"
                  :show-header="false"
                >
                  <el-table-column prop="name" min-width="330px">
                    <template slot-scope="{row,$index}">
                      <div v-on:dblclick="transferClerk(row,$index)">{{row.name}}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
              <el-col :span="4">
                <div class="TheArrow">
                  <div>
                    <span class="iconjiantou_qiehuanzuo iconfont"></span>
                  </div>
                  <div>
                    <span class="iconjiantou_qiehuanyou iconfont"></span>
                  </div>
                </div>
              </el-col>
              <el-col :span="10">
                <div class="SelectName">
                  <i class="iconmorentouxiang iconfont"></i>
                  <span>区域主管</span>
                </div>
                <div class="SelectPrompt">
                  <span>双击名字即可到右侧设置成员为区域文员</span>
                </div>
                <div class="SelectName" style="border-bottom:1px solid #EBEEF5">
                  <i class="iconmorentouxiang iconfont"></i>
                  <span>{{AddRegionData.uName}}</span>
                </div>
                <el-table
                  style="width:100%;text-align:center;"
                  :data="RegionUserData"
                  :show-header="false"
                  empty-text="无数据"
                  class="tablePrompt"
                  height="220px"
                >
                  <el-table-column prop="name" min-width="330px">
                    <template slot-scope="{row,$index}">
                      <div v-on:dblclick="transferClerk2(row,$index)">{{row.name}}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </div>
          <div class="AddRegionBt">
            <el-button
              type="primary"
              size="mini"
              round
              @click="EditrConfirm"
              :loading="loading.EidtorLoading"
            >确认</el-button>
            <el-button type="primary" size="mini" round plain @click="EidtorClose">取消</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!--  -->
    <el-dialog title="项目列表" :visible.sync="projectIsShow" :before-close="projectClose"  width="980px" class="projectRegionChange">
      <el-tabs  v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="未开始" name="first">
        </el-tab-pane>
        <el-tab-pane label="服务中" name="second">
        </el-tab-pane>
        <el-tab-pane label="停止" name="third">
        </el-tab-pane>
        <el-tab-pane label="逾期" name="fourth">
        </el-tab-pane>
      </el-tabs>
     <project-tab ref="msgChild"></project-tab>
    
    </el-dialog>
  </div>
</template>

<script>
 import projectTab from '../../components/region/project.vue'
export default {
  components: {
    projectTab:projectTab
  },
  name: "Region",
  data() {
    var checkCity = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("城市不能为空"));
      } else {
        return callback();
      }
    };
    var checkprovince = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("省不能为空"));
      } else {
        return callback();
      }
    };
    return {
      loading: {
        // 列表
        listloading: false,
        //  区域主管
        RegionUserLoading: false,
        // 确定
        EidtorLoading: false
      },
      RegionTitle: "",
      Regionstatus: true,
      tableData: {
        rows: []
      },
      currpage: 1,
      pagesize: 15,
      name: null,
      valueInput: null,
      AddRegion: false,
      textarea2: "",
      // 新增区域数据
      AddRegionData: {
        mtCompanyId: JSON.parse(sessionStorage.getItem("companyID")).id,
        areaCode: "",
        provinceCode: "",
        areaName: "",
        userId: "",
        clerk: "",
        remark: "",
        userName: "",
        cityCode: ""
      },
      PromptDatas: [],
      RegionUserData: [],
      cityDatas: [],
      shiDatas: [],
      // Regional区域主管
      Regional: [],
      newRegionalDatas: {
        citydata: null,
        userName: null
      },
      AddRules: {
        areaCode: [
          {
            required: true,
            type: "string",
            message: "区域编号不能为空",
            trigger: "blur"
          }
        ]
        // provinceCode: [
        //   { required: true, validator: checkprovince, trigger: "change" }
        // ],
        // citydata: [{ required: true, validator: checkCity, trigger: "change" }],
        // userName: [
        //   { required: true, message: "区域主管不能为空", trigger: "change" }
        // ]
      },
      projectIsShow: false,
      activeName: 'second',
      RegionBtn:{
        RegionBtn23:0,
        RegionBtn24:0,
        RegionBtn25:0,
      }
    };
  },
  created() {
    this.getRegionList();
    this.getProvince();

    var RegionBtn = {}
    this.getButton(22).then(result => {
      if (result.data.statusCode==="1") {
        RegionBtn = result.data.data
        RegionBtn.map((item)=>{
          if(item.id==23){
            this.RegionBtn.RegionBtn23 = item.checked?1:0 
          }else if(item.id==24){
            this.RegionBtn.RegionBtn24 = item.checked?1:0  
          }else if(item.id==25){
            this.RegionBtn.RegionBtn25 = item.checked?1:0  
          }
        })
      }
    });
  },
  mounted() {
    this.getRegionUser();
  },
  methods: {
    // 列表页数量
    handleSizeChange(val) {
      this.pagesize = val;
      this.currpage = 1;
      this.getRegionList();
    },
    // 获取省
    getProvince() {
      var url = "business/common/area/list";
      this.axios.post(url, { code: 0 }).then(res => {
        console.log(res);
        if (res.statusCode == "1") {
          this.cityDatas = res.data;
        }
      });
    },
    // 获取区域主管
    getRegionUser() {
      var url2 = "system/companyuser/getCompanyMembers";
      var param = {
        companyId: JSON.parse(sessionStorage.getItem("companyID")).id,
        roleCode: "REGION_DIRECTOR"
      };
      this.axios.post(url2, param).then(res => {
        if (res.statusCode === "1") {
          this.Regional = res.data;
        } else if (res.statusCode === "0") {
          this.$message(res.message);
        }
      });
    },
    click(val) {
      this.currpage = val;
      this.getRegionList();
    },
    // 上一页
    customerPrev(val) {
      this.currpage = val;
      this.getRegionList();
    },
    // 下一页
    customerNext(val) {
      this.currpage = val;
      this.getRegionList();
    },
    // 编辑区域
    EditRegion(row, index) {
      this.Regionstatus = false;
      this.RegionTitle = "编辑区域";
      this.AddRegionData = row;
      this.AddRegionData.uName = row.name;
      var _this = this;
      var promise = new Promise((resolve, reject) => {
        var url = "enterprise/region/user";
        var param = {
          id: row.id
        };
        _this.axios.post(url, param).then(res => {
          if (res.statusCode == "1" || res.statusCode == "9") {
            _this.RegionUserData = !res.data.regionClerk
              ? []
              : res.data.regionClerk;
            resolve(res.data.regionClerk);
          }
          if (res.statusCode === "1") {
            // _this.AddRegionData.userName = res.data.regionUser.userId;
          } else {
            _this.$message.error(res.message);
          }
        });
      });
      promise
        .then(function(data) {
          var data2;
          !data ? (data2 = []) : (data2 = data);
          var url2 = "system/companyuser/getCompanyMembers";
          var param = {
            companyId: JSON.parse(sessionStorage.getItem("companyID")).id,
            roleCode: "CLERK"
          };
          _this.axios.post(url2, param).then(res => {
            if (res.statusCode !== "1") return;
            var a = res.data.filter(value => {
              return data2.every(item => {
                return value.userId !== item.userId;
              });
            });
            _this.PromptDatas = a;
          });
        })
        .then(function(data) {
          var url = "business/common/area/list";
          _this.axios.post(url, { code: row.provinceCode }).then(res => {
            if (res.statusCode == "1") {
              _this.shiDatas = res.data;
            }
          });
        });
      this.AddRegion = true;
    },
    // 获取列表
    getRegionList() {
      var url = "enterprise/region/list";
      var param = {
        mtCompanyId: JSON.parse(sessionStorage.getItem("companyID")).id,
        pageNum: this.currpage,
        pageSize: this.pagesize,
        name: this.name
      };
      this.axios.post(url, param).then(res => {
        if (res.statusCode == "0") {
          this.$message(res.message);
        } else if (res.statusCode == "1") {
          this.tableData = res.data;
        }
      });
    },
    // 打开新增区域模态框
    AddRegionModal() {
      this.RegionTitle = "新增区域";
      this.Regionstatus = true;
      this.AddRegion = true;
      var url2 = "system/companyuser/getCompanyMembers";
      var param = {
        companyId: JSON.parse(sessionStorage.getItem("companyID")).id,
        roleCode: "CLERK"
      };
      this.axios.post(url2, param).then(res => {
        if (res.statusCode === "1") {
          this.PromptDatas = res.data;
        } else {
          this.PromptDatas = [];
        }
      });
    },
    ChangeProvince(val) {
      var url = "business/common/area/list";
      this.AddRegionData.cityCode = "";
      var param = { code: val };
      this.axios.post(url, param).then(res => {
        if (res.statusCode === "1") {
          this.shiDatas = res.data;
        }
      });
      // this.AddRegionData.provinceCode = val.code;
      // var datas = this.cityDatas.filter(item => {
      //   if (item.code === val.code) return item;
      // });
      // this.shiDatas = datas[0].children;
    },
    searchInput() {
      this.name = this.valueInput;
      this.pageNum = 1;
      this.getRegionList();
    },
    resetInput() {
      this.name = null;
      this.valueInput = "";
      this.pageNum = 1;
      this.getRegionList();
    },
    ChangeCity(val) {
      // this.AddRegionData.cityCode = val;
    },
    ChangeNameRegion(val) {
      var _this = this;
      this.Regional.map(item => {
        if (item.userId === val) return (_this.AddRegionData.uName = item.name);
      });
    },
    // 穿梭框
    transferClerk(...age) {
      this.RegionUserData.push(age[0]);
      this.PromptDatas.splice(age[1], 1);
    },
    transferClerk2(...age) {
      this.PromptDatas.push(age[0]);
      this.RegionUserData.splice(age[1], 1);
    },
    // 新增确定
    EditrConfirm() {
      var a;
      this.$refs["AddRegionData"].validate(valid => {
        if (valid) {
          a = true;
        } else {
          a = false;
        }
      });
      if (!a) return;
      this.loading.EidtorLoading = true;
      var url;
      if (this.Regionstatus) {
        url = "enterprise/region/add";
      } else {
        url = "enterprise/region/update";
      }

      var param = this.AddRegionData;
      var abc = "";
      this.RegionUserData.forEach(item => {
        abc += item.userId + ",";
      });
      abc = abc.substring(0, abc.lastIndexOf(","));
      param.clerk = abc;
      this.axios.post(url, param).then(res => {
        if (res.statusCode) this.loading.EidtorLoading = false;
        if (res.statusCode === "1") {
          this.AddRegionData = {
            mtCompanyId: JSON.parse(sessionStorage.getItem("companyID")).id,
            areaCode: "",
            provinceCode: "",
            cityCode: "",
            areaName: "",
            userId: "",
            clerk: "",
            remark: "",
            userName: ""
          };
          this.RegionUserData = [];
          this.AddRegion = false;
          this.newRegionalDatas = {
            citydata: null,
            userName: null
          };
          this.getRegionList();
        } else if (res.statusCode === "9") {
          this.$message(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    EidtorClose() {
      this.AddRegionData = {
        mtCompanyId: JSON.parse(sessionStorage.getItem("companyID")).id,
        areaCode: "",
        provinceCode: "",
        cityCode: "",
        areaName: "",
        userId: "",
        clerk: "",
        remark: "",
        userName: "",
        provinceCode: "",
        citydata: ""
      };
      this.newRegionalDatas = {
        citydata: null,
        userName: null
      };
      this.getRegionList();
      this.RegionUserData = [];
      this.AddRegion = false;
      this.$refs["AddRegionData"].resetFields();
    },
    DeletRegion(row, i) {
      var url = "enterprise/region/delete";
      var param = row;
      this.$confirm("此操作将永久删除该区域, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.axios.post(url, param).then(res => {
            if (res.statusCode === "1") {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getRegionList();
            } else {
              this.$message(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    projectRegion(row, i) {
      var _this=this;
      this.projectIsShow = true;
      setTimeout(()=>{
         _this.$refs.msgChild.getProjectList(row)
      },100)
    },
    projectClose() {
      this.projectIsShow = false;
      this.activeName='second';
    },
    handleClick(tab,event){
      var _this=this;
      var index=parseInt(tab.index)+1;
      setTimeout(()=>{
         _this.$refs.msgChild.handleClick(index)
      },100)
    }
  }
};
</script>
<style lang="stylus"></style>

