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

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="城市名称" prop="cityName">
        <el-input v-model="queryParams.cityName" placeholder="请输入城市名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="queryParams.keywords" placeholder="请输入关键词" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['ecw:node:create']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['ecw:node:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="排序" align="center" prop="aorder" />
      <el-table-column label="网点编号" align="center" prop="number" />
      <el-table-column label="网点名称" align="center" prop="titleZh" />
      <el-table-column label="网点地址" align="center" prop="addressZh" />

      <el-table-column prop="adminId" label="负责人" align="center">
        <template slot-scope="scope">
          <div>
            <span>{{ scope.row.adminId ? scope.row.adminName : '未设置' }}</span>
            <br>
            <el-button v-if="!scope.row.adminId" type="text" size="mini" @click="setAdminClick(scope.row)">设置主管</el-button>
          </div>
        </template>
      </el-table-column>


      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="CommonStatusEnum.ENABLE" :inactive-value="CommonStatusEnum.DISABLE" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>

     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="warehouse(scope.row)"
                     v-hasPermi="['ecw:node:delete']">仓库</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['ecw:node:update']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 设置主管对话框  -->
      <el-dialog title="设置主管" :visible.sync="setAdminOpen" width="900px" append-to-body>
        <el-table  :data="userList">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="用户名" align="center" prop="username" />
        <el-table-column label="姓名" align="center" prop="nickname" />
        <el-table-column label="手机号" align="center" prop="mobile" />

        <el-table-column prop="loginDate" label="最近操作" align="center">
          <template slot-scope="scope">
            <span>{{ new Date(scope.row.loginDate).format('yyyy-MM-dd hh:mm:ss')}}</span>
            <br>
            <span>{{scope.row.loginIp}}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="setAdmin(scope.row)"
                      >设为主管</el-button>
          </template>
        </el-table-column>
      </el-table>

        <!-- 分页组件 -->
      <pagination v-show="userTotal > 0" :total="userTotal" :page.sync="userQueryParams.pageNo" :limit.sync="userQueryParams.pageSize"
                @pagination="getUserList"/>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="所在地区" prop="area">
          <el-select v-model="form.zhou" placeholder="请选择大洲" @change="changeContinents">
            <el-option
              v-for="item in continentsList"
              :key="item.id"
              :label="item.titleZh"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="form.guojia" placeholder="请选择国家" @change="changeCountry" v-if="form.zhou">
            <el-option
              v-for="item in countryList"
              :key="item.id"
              :label="item.titleZh"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="form.sheng" placeholder="请选择省" @change="changeProvince" v-if="form.guojia">
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.titleZh"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="form.shi" placeholder="请选择城市" @change="changeCity" v-if="form.sheng">
            <el-option
              v-for="item in cityList"
              :key="item.id"
              :label="item.titleZh"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="aorder">
          <el-input v-model="form.aorder" placeholder="请输入排序" />
        </el-form-item>

        <el-form-item label="网点编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入网点编号" />
        </el-form-item>
        
        <el-form-item label="网点名称" prop="titleZh">
          <el-input v-model="form.titleZh" placeholder="请输入网点名称" />
        </el-form-item>
        <el-form-item label="英文名称" prop="titleEn">
          <el-input v-model="form.titleEn" placeholder="请输入英文名称" />
        </el-form-item>
        <el-form-item label="副名称" prop="titlesZh">
          <el-input v-model="form.titlesZh" placeholder="请输入副名称" />
        </el-form-item>
         <el-form-item label="英文副名称" prop="titlesEn">
          <el-input v-model="form.titlesEn" placeholder="请输入英文副名称" />
        </el-form-item>
        <el-form-item label="网点地址" prop="addressZh">
          <el-input v-model="form.addressZh" placeholder="请输入网点地址" />
        </el-form-item>
        <el-form-item label="英文地址" prop="addressEn">
          <el-input v-model="form.addressEn" placeholder="请输入英文地址" />
        </el-form-item>

        <el-form-item label="网点属性" prop="tradeType">
          <el-select v-model="form.tradeType" placeholder="请选择">
            <el-option v-for="dict in regionTypeDatas" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
          </el-form-item>

       <el-form-item label="服务内容" prop="checkList">
          <el-checkbox-group v-model="form.checkList">
            <el-checkbox v-for="dict in transportDatas" :label="dict.value" :key="dict.value" :value="dict.value" name="freight"> {{dict.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>  
 
        
        <el-form-item label="网点详情" prop="contentZh">
          <editor v-model="form.contentZh" :min-height="150"/>
        </el-form-item>
        <el-form-item label="英文详情" prop="contentEn">
          <editor v-model="form.contentEn" :min-height="150"/>
        </el-form-item>
        
        
        <el-form-item label="上班时间" prop="worktime">
          <el-input v-model="form.worktime" placeholder="请输入上班时间" />
        </el-form-item>
       
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createNode, updateNode, deleteNode, getNode, getNodePage, exportNodeExcel } from "@/api/ecw/node";
import { getListTree } from "@/api/ecw/region";
import { getDictDatas, DICT_TYPE } from '@/utils/dict';
import {CommonStatusEnum} from '@/utils/constants'
import {listUser} from "@/api/system/user";
import Editor from '@/components/Editor';

export default {
  name: "Node",
  components: {
    Editor,
  },
  data() {
    var areaCheck = (rule, value, callback) => {
        if(!this.form.zhou) {
          callback(new Error('请选择大洲'));
        } else if(!this.form.guojia){
          callback(new Error('请选择国家/地区'));
        } else if(!this.form.sheng){
          callback(new Error('请选择省市'));
        } else {
          callback();
        }
    };

    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //洲际列表
      continentsList:[],
      //国家列表
      countryList:[],
      //省信息列表
      provinceList: [],
      //市信息列表
      cityList: [],

      // 服务网点列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      //社否显示设置主管
      updateRow:null,
      userList:[],
      userTotal: 0,
      setAdminOpen: false,
      userQueryParams: {
        pageNo: 1,
        pageSize: 10
      },

      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10
      },
      // 表单参数
      form: {
        checkList:[],
      },
      // 表单校验
      rules: {
        area: [{ validator:areaCheck, required: true, trigger: "blur" }],
        aorder: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        number: [{ required: true, message: "网点编号不能为空", trigger: "blur" }],
        titleZh: [{ required: true, message: "网点名称不能为空", trigger: "blur" }],
        titleEn: [{ required: true, message: "英文名称不能为空", trigger: "blur" }],
        titlesZh: [{ required: true, message: "副名称不能为空", trigger: "blur" }],
        titlesEn: [{ required: true, message: "英文副名称不能为空", trigger: "blur" }],
        addressZh: [{ required: true, message: "网点地址不能为空", trigger: "blur" }],
        addressEn: [{ required: true, message: "英文地址不能为空", trigger: "blur" }],
        contentZh: [{ required: true, message: "网点详情不能为空", trigger: "blur" }],
        contentEn: [{ required: true, message: "英文详情不能为空", trigger: "blur" }],
        worktime: [{ required: true, message: "上班时间不能为空", trigger: "blur" }],
        tradeType: [{ required: true, message: '请选择网点属性', trigger: 'change' }],
        checkList: [
            { type: 'array', required: true, message: '请至少选择一个服务内容', trigger: 'change' }
          ],
      },

      // 枚举
      CommonStatusEnum: CommonStatusEnum,
      // 数据字典
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS),
      regionTypeDatas: getDictDatas(DICT_TYPE.ECW_REGION_TYPE),
      transportDatas: getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE)

    };
  },
  created() {
    this.getList();
    this.getContinentsList();
  },

  watch: {
      'form.zhou'(newV, oldV) {
        if(oldV && oldV != newV) {
            this.form.guojia = null;
            this.form.sheng = null;
            this.form.shi = null;
        }
      },

      'form.guojia'(newV, oldV) {
          if(oldV && oldV != newV) {
            this.form.sheng = null;
            this.form.shi = null;
          }
      },

      'form.sheng'(newV, oldV) {
          if(oldV && oldV != newV) {
            this.form.shi = null;
          }
      }
    },

  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getNodePage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    //跳转仓库
    warehouse(row) {
        let nodeId = row.id;
        this.$router.push({
          path:'/node/warehouse-list',
          query: {
            nodeId:nodeId
          }
        })
    },

    //获取用户列表
    getUserList() {
        listUser(this.userQueryParams).then(response => {
            this.userList = response.data.list;
            this.userTotal = response.data.total;
        });
    },

    //设置主管
    setAdminClick(row) {
      this.updateRow = row;
      this.setAdminOpen = true;
      this.getUserList();
    },

    setAdmin(user) {
        this.updateRow.adminId = user.id;
        updateNode(this.updateRow).then(() => {
         this.$set(this.updateRow, 'adminName', user.nickname);
         this.$modal.msgSuccess("设置成功");
         this.setAdminOpen = false;
      }).catch(function() {
         this.$modal.msgSuccess("设置失败");
      });
    },

    getContinentsList() {
        this.queryParams.treeType = 0;
        getListTree(this.queryParams).then(response => {
          this.continentsList = response.data;
      });
    },

    changeContinents(zhou) {
      for(let index in this.continentsList) {
        let continent = this.continentsList[index];
        if(continent.id == zhou) {
          this.countryList = continent.children;
          return;
        }
      }
    },
    changeCountry(countryId) {
      for(let index in this.countryList) {
        let country = this.countryList[index];
        if(country.id == countryId) {
          this.provinceList = country.children;
          return;
        }
      }
    },
    changeProvince(provinceId) {
      for(let index in this.provinceList) {
        let province = this.provinceList[index];
        if(province.id == provinceId) {
          this.cityList = province.children;
          return;
        }
      }
    },

    changeCity(cityId) {
      for(let index in this.cityList) {
        let city = this.cityList[index];
        if(city.id == cityId) {
          
          return;
        }
      }
    },

    handleStatusChange(row) {
      let text = row.status === CommonStatusEnum.ENABLE ? "启用" : "停用";
      this.$modal.confirm('确认要' + text + '编号为' + row.id + '的数据吗?').then(function() {
        return updateNode(row);

      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE
          : CommonStatusEnum.ENABLE;
      });
    },


    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        number: undefined,
        zhou: undefined,
        guojia: undefined,
        sheng: undefined,
        shi: undefined,
        titleZh: undefined,
        titleEn: undefined,
        titlesZh: undefined,
        titlesEn: undefined,
        contentZh: undefined,
        contentEn: undefined,
        addressZh: undefined,
        addressEn: undefined,
        tradeType: undefined,
        freight: undefined,
        worktime: undefined,
        adminId: undefined,
        aorder: undefined,
        checkList: []
        
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务网点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getNode(id).then(response => {
        this.form = response.data;

        this.changeContinents(response.data.zhou);
        this.changeCountry(response.data.guojia);
        this.changeProvince(response.data.sheng);

        let ckList = response.data.freight.split(',');
        this.$set(this.form, 'checkList', ckList);
        
        this.open = true;
        this.title = "修改服务网点";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }

      //逗号拼接运输方式
      var freight = ''
      for(let i = 0; i < this.form.checkList.length; i++) {
            freight += this.form.checkList[i] + ','
          }
      freight = freight.substring(0, freight.length - 1);
      this.form.freight = freight;

        // 修改的提交
        if (this.form.id != null) {
          updateNode(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createNode(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除服务网点编号为"' + id + '"的数据项?').then(function() {
          return deleteNode(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有服务网点数据项?').then(() => {
          this.exportLoading = true;
          return exportNodeExcel(params);
        }).then(response => {
          this.$download.excel(response, '${table.classComment}.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
