<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 :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="is_default"/>
        <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"
              @click="handleUpdate(scope.row)"
            >修改
            </el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @pagination="getList"
      />
      <!-- 添加或修改freight对话框 -->
      <el-dialog :title="title" :visible.sync="isOpen" v-if="isOpen" width="70%" class="freightTemplate-add">
        <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,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // freight表格数据
        freightList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        isOpen: false,
        // 查询参数
        queryParams: {
          page: 1,
          limit: 20,
          seller_id: null,
          name: null,
          sort: null,
          is_default: null,
          charge_type: null,
          dispatching: null,
          dis_dispatching: 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.charge_type
        var optDess = ''
        if (typese == 1) {
          optDess = "按重量"
        } else if (typese == 2) {
          optDess = "按数量"
        }
        return optDess
      },
      //格式化状态
      formatDefault(row) {
        var types = row.is_default
        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() {
        listFreight(this.queryParams).then(res => {
          if(res.data) {
            //
            this.freightList = res.data.list;
            this.total = res.data.count;
          }
        });
      },
      // 取消按钮
      cancel() {
        this.isOpen = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: 0,
          seller_id: null,
          name: null,
          sort: null,
          is_default: null,
          charge_type: null,
          dispatching: null,
          dis_dispatching: null,
          publish: null,
          created: null,
          modified: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 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 >= 50) {
          this.$message({ message: '您已经有50个运费模板了，暂时不再支持更多！',type: 'warning'});
          return;
        }
        this.reset();
        this.isOpen = true;
        this.form = {
          id: 0,
          sort: 0,
          name: "",
          is_default: 0,
          charge_type: 0,
          dispatching: [
            {
              a: "全国",
              f: 500,
              fp: 10,
              n: 100,
              np: 5,
            }
          ],
          dis_dispatching: "",
          publish: 0,
        };
        this.title = "添加运费模板";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id
        getFreight(id).then(res => {
          //let formdate = response.data
          //response.data.dispatching = JSON.parse(formdate.dispatching)
          if(res.code == 1) {
            this.form = res.data
            this.isOpen = true;
            this.title = "修改运费模板";
          }else {
            this.$message({type:'error',message: res.message ? res.message : '获取运费模板详情失败'});
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {

          if (valid) {
            if (this.form.id != 0) {
              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(async()=> {
          let delResult = await delFreight(ids);
          if(delResult.code === 1) {
            this.$message({type: 'success',message: '删除成功'});
            this.getList();
          } else {
            this.$message({type: 'error',message: delResult.msg ? delResult.msg : '删除失败'});
          }
        }).catch(()=> {});
      },
    } //methods结束
  };
</script>
<style scoped lang="scss" type="text/stylus">
  .freightTemplate-add {
    /deep/.el-dialog {
      height: 80%;
      overflow : hidden;
    }
    /deep/.el-dialog__body{
      height: calc(100% - 60px);
      overflow-x: hidden;
      overflow-y: scroll;
    }
  }
</style>
