<template>
  <div class="app-container">
    <!-- 筛选条件 -->
    <div class="screen-container">
      <div class="top clearfix">
        <div class="title fl">条件筛选</div>
      </div>
      <el-form ref="screenForm" :model="screenForm" label-width="70px" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="screenForm.name" placeholder="请输入模板名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="screenForm.status" placeholder="全部">
                <el-option label="全部" value=""></el-option>
                <el-option :label="item.label" :value="item.value" v-for="(item, index) in select_status" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="创建时间" prop="createDate">
              <el-date-picker
                v-model="screenForm.createDate"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="isOpen ? 24 : 12" :lg="isOpen ? 24 : 6" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="mymain-container">
      <template>
        <el-alert type="info" title="商品关联运费模板" :closable="false">
          <template slot="">
            <div class="description">1、商品关联设置：每件商品，仅可设置一种运费收取方式，即：统一运费，或指定运费模板；</div>
            <div class="description">2、统一运费：按商品一次计收运费；如：统一运费10元，买家单笔订单购买N件，均只收取10元运费；</div>
            <div class="description">3、运费模板：选择相应的运费模板，即可指定该商品，可配送至相应区域，并按规则收取相应运费。</div>
          </template>
        </el-alert>
      </template>
      <div class="btn-group clearfix" style="margin-top: 20px;">
        <div class="fl">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addOrEdit('add')">新增运费模版</el-button>
        </div>
        <div class="fr" />
      </div>
      <div class="table">
        <el-table v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>
          <el-table-column align="center" label="模板名称" prop="name" min-width="180"></el-table-column>
          <el-table-column align="center" label="创建人" prop="createUserName" min-width="100"></el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" min-width="120"></el-table-column>
          <el-table-column align="center" label="状态" prop="status">
            <template slot-scope="scope">
              {{ scope.row.status ? '已启用' : '已禁用' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" fixed="right" min-width="100">
            <template slot-scope="scope">
              <el-button type="text" style="margin-right: 10px;" @click="addOrEdit('edit', scope.row.freightTemplateId)">编辑</el-button>
              
              <el-popconfirm v-if="scope.row.status" style="margin-right: 10px;" title="确定禁用吗？" @onConfirm="changeStatus(scope.row.freightTemplateId, 0)" >
                <el-button slot="reference" type="text">禁用</el-button>
              </el-popconfirm>
              <el-popconfirm v-else style="margin-right: 10px;" title="确定启用吗？" @onConfirm="changeStatus(scope.row.freightTemplateId, 1)" >
                <el-button slot="reference" type="text">启用</el-button>
              </el-popconfirm>
              
              <el-popconfirm title="确定删除吗？" @onConfirm="handleDelete(scope.row.freightTemplateId)">
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 新增编辑 -->
    <el-dialog :title="addFormType === 'add' ? '新增模板':'编辑模板'" :visible.sync="addFormVisible" :show-close="false" width="80%" top="10vh" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="left" label-width="80px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="addForm.name" autocomplete="off" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item label="配送区域" prop="region">
          <el-form :model="paramsForm" ref="regionForm" :rules="paramsForm.paramsRules">
            <el-table :data="paramsForm.params" height="400" style="width: 100%" highlight-current-row class="detailTable">
              <el-table-column label="省" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.province }}</span>
                </template>
              </el-table-column>
              <el-table-column label="市" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.city }}</span>
                </template>
              </el-table-column>
              <el-table-column label="首件(个)" align="center" :render-header="(h,obj) => renderHeader(h,obj,'firstLimit')">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'params.' + scope.$index + '.firstLimit'"
                    :rules="paramsForm.paramsRules.min">
                    <el-input v-model.number="scope.row.firstLimit" size="small"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="运费(元)" align="center" :render-header="(h,obj) => renderHeader(h,obj,'firstAmount')">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'params.' + scope.$index + '.firstAmount'"
                    :rules="paramsForm.paramsRules.min">
                    <el-input v-model.number="scope.row.firstAmount" size="small"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="续件(个)" align="center" :render-header="(h,obj) => renderHeader(h,obj,'continuousLimit')">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'params.' + scope.$index + '.continuousLimit'"
                    :rules="paramsForm.paramsRules.min">
                    <el-input v-model.number="scope.row.continuousLimit" size="small"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="续费(元)" align="center" :render-header="(h,obj) => renderHeader(h,obj,'continuousAmount')">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'params.' + scope.$index + '.continuousAmount'"
                    :rules="paramsForm.paramsRules.min">
                    <el-input v-model.number="scope.row.continuousAmount" size="small"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" style="margin-left: 10px;" @click="remove(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
          <el-button @click="innerVisible = true;" style="margin-top: 10px;" type="primary" size="small">添加地区</el-button>
        </el-form-item>
      </el-form>

      <!-- 选择地区 -->
      <el-dialog title="选择地区" width="300px" :visible.sync="innerVisible" append-to-body @close="clearNode">
        <el-tree
          style="max-height: 400px; overflow-y: scroll;"
          class="filter-tree"
          :data="regionTree"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          ref="tree">
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addDetail">添 加</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { COMMON_SELECT } from '@/utils/select_data'
import { getList, deleteFreight, addOrEditFreight, getFreightDetail, getRegionTree, changeFreightStatus } from "@/api/freight";

export default {
  name: "index",
  data() {
    return {
      isOpen: false, // 是否展开条件筛选
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      select_status: COMMON_SELECT.FREIGHT_CURRENT_TYPE,
      editId:  null,
      addFormType: 'add',
      addFormVisible: false,
      screenForm: { // 筛选表单数据
        name: '', // 模板名称
        status: '', // 状态
        createDate: '', // 创建时间
      },
      addForm: {
        name: '',
        status: '',
        freightTemplateDetails: []
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
      },
      paramsForm: {
        params: [

        ],
        paramsRules: {
          min: [
            { required: true, message: '请输入数值', trigger: 'blur' },
            // { type: 'number', min: 0, max: 100, message: '范围(0-100)', trigger: 'blur' }
          ]
        }
      },
      innerVisible: false,
      regionTree: null,
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      search: ''
    }
  },
  created() {
    this.getList();
    this.getTree();
  },
  methods: {
    renderHeader(h, { column, $index }, type){
      let that = this;
      return h(
        'div',
        [
          h('span', column.label),
          h('el-button', {
            props: {
              type: 'text',
              size: 'small',
            },
            style:'color:#409EFF; margin-left:5px;',
            on: {
              click: function() {
                that.changeInput(type);
              }
            }
          }, '统一修改')
        ],
      )
      // return (
      //   <div style="">
      //     <span>{column.label}</span>
      //     <el-button size="small" type="text" onClick={this.changeInput}>统一修改</el-button>
      //   </div>
      // )
    },

    changeInput(type) {
      const typeMap = {
        firstLimit: '首件',
        firstAmount: '运费',
        continuousLimit: '续件',
        continuousAmount: '续费'
      }
      this.$prompt('请输入'+typeMap[type], '编辑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: function(value) {
          if(!value) return '请输入'+typeMap[type]
        },
      }).then(({ value }) => {
        this.paramsForm.params.forEach(item => {
          item[type] = value;
        })
      }).catch(() => {});
    },

    // 获取范围
    getTree() {
      getRegionTree().then((res) => {
        this.regionTree = res.data
        this.regionTree.forEach(value => {
          value.child.forEach(childValue => {
            delete childValue.child
          })
        })
      })
    },
    // 查询列表
    getList() {
      this.listLoading = true;

      let params = {
        name: this.screenForm.name,
        startTime: this.screenForm.createDate[0] ? this.screenForm.createDate[0] : null,
        endTime: this.screenForm.createDate[1] ? this.screenForm.createDate[1] : null,
        status: this.screenForm.status,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      getList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },
    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      this.getList();
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      this.getList();
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    // 操作 - 删除
    handleDelete(id) {
      deleteFreight({ freightTemplateId: id }).then(res => {
        this.getList();
        this.$successMsg();
      })
    },

    // 新增编辑
    addOrEdit(type, id) {
      this.addFormType = type;
      this.addFormVisible = true;
      if(type == 'edit') {
        this.editId = id;
        getFreightDetail({ freightTemplateId: id }).then(res => {
          this.addForm = {
            name: res.data.name,
            status: res.data.status,
            freightTemplateDetails: res.data.freightTemplateDetails
          }
          this.paramsForm.params = this.addForm.freightTemplateDetails
        })
      }
    },
    // 取消 新增编辑
    cancelAddForm(){
      this.addFormVisible = false
      this.$refs.addForm.resetFields()
      this.addForm.freightTemplateDetails = []
      this.paramsForm.params = []
    },
    // 提交 新增编辑
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$refs.regionForm.validate((innerValid) => {
            if (innerValid) {
              let params = {
                name: this.addForm.name,
                freightTemplateDetails: this.paramsForm.params
              }
              if(this.addFormType == 'edit') {
                params.freightTemplateId = this.editId;
                addOrEditFreight(params).then(res => {
                  this.cancelAddForm();
                  this.getList();
                  this.$successMsg('编辑成功');
                })
              }else {
                addOrEditFreight(params).then(res => {
                  this.cancelAddForm();
                  this.getList();
                  this.$successMsg('新增成功');
                })
              }
            }
          })
        }
      })
    },
    addDetail() {
      this.innerVisible = false
      this.$refs.tree.getCheckedNodes(true, false).forEach(value => {
        console.log(value);
        let province = value.parentName;
        let city = value.name;
        let exist = this.paramsForm.params.find((obj) => {
          return obj.province === province && obj.city === city
        })
        if (!exist) {
          this.paramsForm.params.push({
            province: province,
            city: city,
            firstLimit: 1,
            firstAmount: 1,
            continuousLimit: 1,
            continuousAmount: 1
          })
        }
      })
    },
    remove(index) {
      this.paramsForm.params.splice(index, 1)
    },
    clearNode() {
      this.$refs.tree.setCheckedKeys([])
      let node = this.$refs.tree.store.nodesMap
      // 循环所有节点，将需要收起的节点数据的 expanded 属性设置为false
      for (let key in node) {
        node[key].expanded = false;
      }
    },

    // 操作 - 更改状态(type: 禁用0，启用1)
    changeStatus(id, type) {
      type = type ? true : false
      changeFreightStatus({freightTemplateId: id, status: type}).then(res => {
        this.getList();
        this.$successMsg();
      })
    },
  }
}
</script>

<style>
.detailTable .cell{
  overflow: visible;
}
.detailTable .el-form-item{
  margin-bottom: 0;
}
.detailTable .el-form-item__error{
  padding-top:0;
  margin-top:-3px;
}
</style>

<style scoped>
.description {
  margin-top: 10px;
}
</style>