<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form :inline="true" class="queryFormInline">
          <el-row :span="24" type="flex" align="middle" justify="space-between">
            <el-col :span="20">
              <p style="font-size: 18px; float:left;">运费模板</p>
            </el-col>
            <el-col :span="4">
              <div style="float: right">
                <el-button
                  style="float:right;margin-left: 10px;"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                >删除
                </el-button>
                <el-button
                  style="float:right;margin-left: 20px;"
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                >新增
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <el-table v-loading="loading" :data="freightList" :height="tableHeight" @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="Sort"/>
        <el-table-column label="是否是默认模板" align="center" :formatter="formatDefault" prop="IsDefault"/>
        <el-table-column label="类型" align="center" :formatter="formatType" prop="ChargeType"/>
        <el-table-column label="启用状态" align="center" :formatter="formaStatus" prop="Publish"/>
        <el-table-column label="创建时间" align="center" :formatter="formatTime" prop="Created"/>
        <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)"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除
            </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"
      />
      <!-- 添加或修改freight对话框 -->
      <el-dialog :title="title" :visible.sync="isOpen" v-if="isOpen" width="70%">
        <IndexBtn :option="form" @closeIndexbtn="closeDialog"/>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
  import IndexBtn from './indexbtn'
  import {listFreight, getFreight, delFreight, addFreight, updateFreight} from '@/api/module/freight'
  import {dateFormat} from '@/utils'

  export default {
    name: "freight",
    data() {
      return {
        fullHeight: 0,
        tableHeight: 0,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // freight表格数据
        freightList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        isOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          seller_id: null,
          name: null,
          sort: null,
          is_default: null,
          charge_type: null,
          dispatching: null,
          disdispatching: null,
          publish: null,
          created: null,
          modified: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            {required: true, message: "模板名称不能为空", trigger: "blur"}
          ],
        }
      };
    },
    components: {
      IndexBtn
    },
    created() {
      this.getList();
      this.$nextTick(() => {
        this.fullHeight = document.getElementsByClassName('box-card')[0].clientHeight
      })

    },
    watch: {
      fullHeight(val) {
        let formHeight = document.getElementsByClassName('clearfix')[0].clientHeight
        this.tableHeight = val - formHeight - 120;
      }
    },
    methods: {
      closeDialog(val) {
        this.isOpen = val;
        this.getList();
      },
      // 模板是否启用状态
      formaStatus(row) {
        let isPublish = row.Publish;
        let publish = '';
        if(isPublish === 1) {
          publish = '启用';
        }
        if(isPublish === 0) {
          publish = '禁用';
        }
        return publish
      },
      formatType(row) {
        var typese = row.ChargeType
        var optDess = ''
        if (typese == 1) {
          optDess = "按重量"
        } else if (typese == 2) {
          optDess = "按数量"
        }
        return optDess
      },
      //格式化状态
      formatDefault(row) {
        var types = row.IsDefault
        var optDes = ''
        if (types == 1) {
          optDes = "是"
        } else if (types == 0) {
          optDes = "否"
        }
        return optDes
      },
      //格式化时间
      formatTime(row) {
        var Time = row.Created
        var newtime = ""
        if (Time > 0) {
          newtime = dateFormat(Time * 1000, "Y-m-d H:i:s");
        }
        return newtime
      },
      /** 查询freight列表 */
      getList() {
        this.loading = true;
        listFreight(this.queryParams).then(response => {
          this.freightList = response.data.data.list;
          this.total = response.data.data.count;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.isOpen = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          seller_id: null,
          name: null,
          sort: null,
          is_default: null,
          charge_type: null,
          dispatching: null,
          disdispatching: null,
          publish: null,
          created: null,
          modified: null
        };
        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() {
        if(this.total >= 20) {
          this.$message({ message: '您已经有20个运费模板了，暂时不再支持更多哦！',type: 'warning'});
          return;
        }
        this.reset();
        this.isOpen = true;
        this.form = {
          Id: 0,
          Sort: 0,
          Name: "0",
          IsDefault: 0,
          ChargeType: 0,
          Dispatching: [
            {
              a: "全国",
              f: 500,
              fp: 10,
              n: 100,
              np: 5,
            }
          ],
          Disdispatching: "",
          Publish: 0,
        };
        this.title = "添加运费模板";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.Id
        getFreight(id).then(response => {
          let formdate = response.data
          response.data.Dispatching = JSON.parse(formdate.Dispatching)
          console.log("点击修改获取的数据：",response.data.Dispatching);
          this.form = response.data
          this.isOpen = true;
          this.title = "修改运费模板";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateFreight(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess("修改成功");
                  this.isOpen = false;
                  this.getList();
                }
              });
            } else {
              addFreight(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess("新增成功");
                  this.isOpen = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /*
      * publish  启用禁用状态  1是启用，0 禁用
      * */
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.Id || this.ids;
        this.$confirm('是否确认删除运费模板编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delFreight(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {});
      },
    } //methods结束
  };
</script>
<style scoped lang="scss" type="text/stylus">

</style>
