<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="node" >
        <el-select v-model="queryParams.nodeId" placeholder="所属网点" :disabled="nodeId ? true : false" clearable>
          <el-option v-for="node in nodeList" :key="node.id" :label="node.titleZh" :value="node.id"/>
        </el-select>
      </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:warehouse: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:warehouse: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="number" />
      <el-table-column label="仓库名称" align="center" prop="titleZh" />
      <el-table-column label="仓库容量(m)³" align="center" prop="volume" />
      <el-table-column label="仓库地址" align="center" prop="addressZh" />

      <el-table-column prop="head" label="负责人" align="center">
        <template slot-scope="scope">
          <div>
            <span>{{ scope.row.head }}</span>
            <br>
            <span>{{ scope.row.tell }}</span>
          </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" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['ecw:warehouse: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="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="所属网点" prop="nodeId">
         <el-select v-model="form.nodeId" placeholder="请选择所属网点" :disabled="(nodeId || isUpdate) ? true : false" clearable>
          <el-option v-for="node in nodeList" :key="node.id" :label="node.titleZh" :value="node.id"/>
         </el-select>
        </el-form-item>

        <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="sort">
          <el-input v-model="form.sort" type="number" 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="qianzhui">
          <el-input v-model="form.qianzhui" 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="head">
          <el-input v-model="form.head" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="tell">
          <el-input v-model="form.tell" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="容量" prop="volume">
          <el-input v-model="form.volume" placeholder="请输入容量">
            <template slot="append">m³</template>
          </el-input>
        </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="请选择" :disabled="(nodeId || isUpdate) ? true : false">
            <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" name="freight"> {{dict.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>  
        
        <el-form-item label="img" prop="img">
          <el-input v-model="form.img" placeholder="请输入图片" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" 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 { createWarehouse, updateWarehouse, deleteWarehouse, getWarehouse, getWarehousePage, exportWarehouseExcel } from "@/api/ecw/warehouse";
import { getNodePage } from "@/api/ecw/node";
import { getListTree } from "@/api/ecw/region";
import { getDictDatas, DICT_TYPE } from '@/utils/dict';
import {CommonStatusEnum} from '@/utils/constants'

export default {
  name: "Warehouse",
  components: {
  },
  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,

      //洲际列表
      continentsList:[],
      //国家列表
      countryList:[],
      //省信息列表
      provinceList: [],
      //市信息列表
      cityList: [],

      // 总条数
      total: 0,
      // 仓库列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],

      isUpdate: false,

      nodeList: [],

      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        number: null,
        titleZh: null,
        titleEn: null,
        volume: null,
        addressZh: null,
        addressEn: null,
        zhou: null,
        guojia: null,
        sheng: null,
        shi: null,
        head: null,
        tell: null,
        tradeType: null,
        freight: null,
        remark: null,
        sort: null,
        status: null,
      },
      // 表单参数
      form: {checkList:[],},
      // 表单校验
      rules: {
        nodeId: [{ required: true, message: "服务网点不能为空", trigger: "blur" }],
        area: [{ validator:areaCheck, required: true, trigger: "blur" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        number: [{ required: true, message: "仓库编号不能为空", trigger: "blur" }],
        titleZh: [{ required: true, message: "仓库名称不能为空", trigger: "blur" }],
        titleEn: [{ required: true, message: "英文名称不能为空", trigger: "blur" }],
        head: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
        tell: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
        volume: [{ required: true, message: "容量不能为空", trigger: "blur" }],
        addressZh: [{ required: true, message: "仓库地址不能为空", trigger: "blur" }],
        addressEn: [{ required: true, message: "英文地址不能为空", trigger: "blur" }],
        tradeType: [{ required: true, message: '请选择网点属性', trigger: 'change' }],
        checkList: [
            { type: 'array', required: true, message: '请至少选择一个服务内容', trigger: 'change' }
          ],
      },
      nodeId: this.$route.query.nodeId,

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

  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;
          }
      }
    },

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

    getSelectNode(nodeId) {
      for(let index in this.nodeList) {
        let node = this.nodeList[index];
        if(node.id == nodeId) return node;
      }
    },

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

    //获取网点列表
    getNodeList() {
      let params = {pageNo:1, pageSize:100};
      getNodePage(params).then(response => {
          this.nodeList = response.data.list;
      });
    },

      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 updateWarehouse(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,
        pid: undefined,
        number: undefined,
        qianzhui: undefined,
        titleZh: undefined,
        titleEn: undefined,
        volume: undefined,
        addressZh: undefined,
        addressEn: undefined,
        zhou: undefined,
        guojia: undefined,
        sheng: undefined,
        shi: undefined,
        head: undefined,
        tell: undefined,
        tradeType: undefined,
        freight: undefined,
        remark: undefined,
        sort: undefined,
        status: undefined,
        img: undefined,
        checkList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isUpdate = false;
      if(this.nodeId) {
        //把已现在的网点的一些属性赋值给仓库
          this.form.nodeId = this.queryParams.nodeId;
          let node = this.getSelectNode(this.form.nodeId);
          this.form.zhou = node.zhou;
          this.form.guojia = node.guojia;
          this.form.sheng = node.sheng;
          this.form.shi = node.shi;
          this.form.tradeType = node.tradeType;

          this.form.checkList = node.freight.split(',');
         
          this.changeContinents(this.form.zhou);
          this.changeCountry(this.form.guojia);
          this.changeProvince(this.form.sheng);
      }
      this.open = true;
      this.title = "添加仓库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getWarehouse(id).then(response => {
        this.form = response.data;

        let ckList = response.data.freight.split(',');
        this.$set(this.form, 'checkList', ckList);

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

      
        
        this.isUpdate = true;

        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) {
          updateWarehouse(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createWarehouse(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 deleteWarehouse(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 exportWarehouseExcel(params);
        }).then(response => {
          this.$download.excel(response, '${table.classComment}.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
