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

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:shippingTemplates:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:shippingTemplates:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:shippingTemplates:remove']"
        >删除</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  height="500" border v-loading="loading" :data="shippingTemplatesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板ID" align="center" prop="id" />
      <el-table-column label="模板名称" align="center" prop="name" />
      <el-table-column label="计费方式" align="center" prop="type" >
          <template slot-scope="scope">
              <el-tag prop="type" v-for="(item, index) in typeOptions"    v-if="scope.row.type==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="指定包邮开关" align="center" prop="appoint" >
          <template slot-scope="scope">
              <el-tag prop="type" v-for="(item, index) in appointOptions"    v-if="scope.row.appoint==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" />
      <el-table-column label="排序" align="center" prop="sort" />
      <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="['store:shippingTemplates:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:shippingTemplates:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运费模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="计费方式" prop="type">
            <el-radio-group v-model="form.type" >
               <el-radio :label="item.dictValue" v-for="item in typeOptions" >{{item.dictLabel}}</el-radio>-radio>
            </el-radio-group>
        </el-form-item>
        <el-row :gutter="24" type="flex">
          <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
            <el-form-item class="label" label="配送区域及运费：" props="state">
              <el-table
                ref="table"
                :data="templateList"
                empty-text="暂无数据"
                border
              >
                <el-table-column prop="regionName" label="可配送区域" width="130" />
                <el-table-column prop="first" label="首件" width="120">
                  <template slot="header" slot-scope="scope">
                    <span v-if="form.type == 1">首件</span>
                    <span v-else-if="form.type == 2">首件重量(KG)</span>
                    <span v-else>首件体积(m³)</span>
                  </template>
                  <template slot-scope="scope">
                    <span><el-input type="text" v-model="scope.row.first" /></span>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="运费（元）" width="110">
                  <template slot-scope="scope">
                    <span><el-input type="text" v-model="scope.row.price"/></span>
                  </template>
                </el-table-column>
                <el-table-column prop="_continue" label="续件" width="120">
                  <template slot="header" slot-scope="scope">
                    <span v-if="form.type == 1">续件</span>
                    <span v-else-if="form.type == 2">续件重量(KG)</span>
                    <span v-else>续件体积(m³)</span>
                  </template>
                  <template slot-scope="scope">
                    <span><el-input type="text" v-model="scope.row.continues"/></span>
                  </template>
                </el-table-column>
                <el-table-column prop="continuePrice" label="续费（元）" width="110">
                  <template slot-scope="scope">
                    <span><el-input type="text" v-model="scope.row.continuePrice"/></span>
                  </template>
                </el-table-column>
                <el-table-column  label="操作">
                  <template slot-scope="scope">
                    <a  @click="delCity(scope.$index,1)">删除</a>
                  </template>
                </el-table-column>

              </el-table>
              <el-row type="flex" class="addTop">
                <el-col>
                  <el-button size="small" type="primary" icon="md-add" @click="addCity(1)">单独添加配送区域</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
            <el-form-item label="指定包邮：" prop="appoint">
              <el-radio-group v-model="form.appoint" >
                    <el-radio :label="item.dictValue" v-for="item in appointOptions" >{{item.dictLabel}}</el-radio>-radio>
                  </el-radio-group>
              <el-table
                ref="table"
                :data="appointList"
                empty-text="暂无数据"
                border
                v-if="form.appoint === '1'"
              >
                <el-table-column prop="placeName" label="选择地区" />
                <el-table-column prop="a_num" label="包邮件数" width="120" >
                  <template slot="header" slot-scope="scope">
                    <span v-if="form.type == 1">包邮件数</span>
                    <span v-else-if="form.type == 2">包邮重量(KG)</span>
                    <span v-else>包邮体积(m³)</span>
                  </template>
                  <template slot-scope="scope">
                    <span><el-input type="text" v-model="scope.row.number"/></span>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="包邮金额（元）" width="120">
                  <template slot-scope="scope">
                    <span><el-input type="text" v-model="scope.row.price"/></span>
                  </template>
                </el-table-column>
                <el-table-column  label="操作">
                  <template slot-scope="scope">
                    <a  @click="delCity(scope.$index ,2)">删除</a>
                  </template>
                </el-table-column>

              </el-table>
              <el-row type="flex" v-if="form.appoint === '1'">
                <el-col>
                  <el-button size="small" type="primary" icon="md-add" @click="addCity(2)">单独指定包邮</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排序" prop="sort">
          <el-input-number :min="0"  v-model="form.sort" 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>
    <CityZm ref="city" @selectCity="selectCity" :type="type"></CityZm>
  </div>
</template>

<script>
import { listShippingTemplates, getShippingTemplates, delShippingTemplates, addShippingTemplates, updateShippingTemplates, exportShippingTemplates } from "@/api/hisStore/shippingTemplates";
import CityZm from '@/components/City/indexZm'
export default {
  name: "ShippingTemplates",
  components: {
    CityZm
  },
  data() {
    return {
      type:0,
      appointList:[],
      templateList:[],
      appointOptions:[],
      typeOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运费模板表格数据
      shippingTemplatesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        regionInfo: null,
        appoint: null,
        appointInfo: null,
        isDel: null,
        sort: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getDicts("store_shipping_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("store_shipping_appoint").then((response) => {
      this.appointOptions = response.data;
    });
    this.getList();
  },
  methods: {
    delCity (index,type) {
      if (type === 1) {
        this.templateList.splice(index, 1);
      } else {
        this.appointList.splice(index, 1);
      }
    },
    selectCity: function (data, type) {
      let cityName = data.map(function (item) {
        return item.name;
      }).join(';');
      switch (type) {
        case 1:
          this.templateList.push({
            region: data,
            regionName: cityName,
            first: 1,
            price: 0,
            continues: 1,
            continuePrice: 0
          });
          break;
        case 2:
          this.appointList.push({
            place: data,
            placeName: cityName,
            number: 0,
            price: 0
          });
          break;
      }
    },
    // 单独添加配送区域
    addCity (type) {
      // 获取已选择的城市数据
      let selectedCities = [];
      if (type === 1) {
        // 配送区域
        this.templateList.forEach(item => {
          if (item.region && item.region.length > 0) {
            selectedCities = selectedCities.concat(item.region);
          }
        });
      } else {
        // 指定包邮
        this.appointList.forEach(item => {
          if (item.place && item.place.length > 0) {
            selectedCities = selectedCities.concat(item.place);
          }
        });
      }
      this.$refs.city.addressView = true;
      this.type = type;
      this.$refs.city.selectedCities = selectedCities;
      this.$refs.city.getCityList()
    },
    /** 查询运费模板列表 */
    getList() {
      this.loading = true;
      listShippingTemplates(this.queryParams).then(response => {
        this.shippingTemplatesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: "1",
        appoint: "0",
        createTime: null,
        updateTime: null,
        isDel: null,
        sort: null
      };
      this.templateList = [
        {
          region: [
            {
              name: '默认全国',
              cityId: 0
            }
          ],
          regionName: '默认全国',
          first: 1,
          price: 0,
          continues: 1,
          continuePrice: 0
        }
      ];
      this.appointList=[],
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加运费模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getShippingTemplates(id).then(response => {
        this.form = response.data;
        this.form.type = response.data.type.toString();
        this.form.appoint = response.data.appoint.toString();
        this.appointList=JSON.parse(this.form.appointInfo)
        this.templateList=JSON.parse(this.form.regionInfo)
        this.open = true;
        this.title = "修改运费模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.regionInfo=this.templateList;
          this.form.appointInfo=this.appointList;
          if (this.form.id != null) {
            updateShippingTemplates(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addShippingTemplates(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除运费模板编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delShippingTemplates(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有运费模板数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportShippingTemplates(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
