<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select v-model="listQuery.cityId" clearable style="width: 200px" class="filter-item" placeholder="请选择所属城市"
        filterable>
        <el-option v-for="item in citys" :key="item.id" :label="item.cityName" :value="item.id" />
      </el-select>

      <el-button v-permission="['GET /admin/goodsServiceFee/getFeeList']" class="filter-item" type="primary"
        icon="el-icon-search" @click="getList">查找</el-button>
      <el-button v-permission="['POST /admin/goodsServiceFee/addFee']" class="filter-item" type="success"
        icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="商品id" prop="goodsId" />

      <el-table-column align="center" label="规格id" prop="productId" />
      <el-table-column align="center" label="规格名称" prop="productName" />
      <el-table-column align="center" label="所属城市" prop="cityName" />

      <el-table-column align="center" label="起止日期" width="200">
        <template slot-scope="scope">{{ scope.row.validityStart }} 至 {{ scope.row.validityEnd }}</template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" />

      <el-table-column align="center" label="创建时间" prop="createTime" />

      <el-table-column align="center" label="操作" width="280">
        <template slot-scope="scope">
          <el-button v-permission="['GET /admin/goodsServiceFee/updateFee']" type="success" size="mini" plain
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-permission="['GET /admin/goodsServiceFee/delete']" type="danger" size="mini" plain
            @click="handleDel(scope.row)">删除</el-button>
          <el-button v-permission="['GET /admin/goodsServiceFee/batchCopy']" type="primary" size="mini" plain
            @click="handleCopy(scope.row)">一键复制</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="feeDiaVisible" :title="diaType == 'add' ? '添加计提' : '编辑计提'" width="700px">
      <el-form ref="dataForm" :rules="formRules" :model="dataForm" status-icon label-position="left" label-width="100px"
        style="margin-left:50px;">
        <el-form-item label="选择规格" prop="productId">
          <el-select v-model="dataForm.productId" clearable style="width:400px;" placeholder="请选择所属城市" filterable>
            <el-option v-for="item in productList" :key="item.id" :label="item.specifications[0]" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择城市" prop="cityId">
          <el-select v-model="dataForm.cityId" clearable style="width:400px;" placeholder="请选择所属城市" filterable>
            <el-option v-for="item in citys" :key="item.id" :label="item.cityName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="起止日期" prop="validityTime">
          <el-date-picker style="width:400px;" v-model="dataForm.validityTime" type="daterange" class="filter-item"
            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"
            value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="计提金额" prop="serviceFee">
          <el-input v-model="dataForm.serviceFee" type="number" placeholder="请输入计提金额" style="width:400px;">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark" type="textarea" rows="3" placeholder="请输入备注"
            style="width:400px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="feeDiaVisible = false">取消</el-button>
        <el-button type="primary" @click="confServiceFee()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 一键复制 -->
    <el-dialog :visible.sync="copyDiaVisible" title="一键复制" width="700px">
      <el-form ref="copyForm" :rules="copyRules" :model="copyForm" status-icon label-position="left" label-width="100px"
        style="margin-left:50px;">
        <el-form-item label="选择城市" prop="cityIds">
          <el-select v-model="copyForm.cityIds" clearable style="width:400px;" placeholder="请选择所属城市" filterable multiple>
            <el-option v-for="item in citys" :key="item.id" :label="item.cityName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="copyDiaVisible = false">取消</el-button>
        <el-button type="primary" @click="confCopyFee()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getFeeList,
  addFee,
  batchCopy,
  updateFee,
  deleteFee
} from "@/api/goods";
import { getProduct } from "@/api/order";
import { listAllCity } from "@/api/city";
import { formatDate } from "@/utils/date";

export default {
  name: "serviceFee",
  components: {},
  filters: {},
  data() {
    return {
      list: [],
      listQuery: {
        cityId: ""
      },
      goodsId: "",
      citys: [],
      productList: [],
      diaType: "add",
      feeDiaVisible: false,
      dataForm: {
        productId: "",
        cityId: "",
        validityTime: [],
        serviceFee: ""
      },
      copyDiaVisible: false,
      copyForm: {
        cityIds: []
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      formRules: {
        productId: [{ required: true, message: "请选择规格", trigger: "blur" }],
        cityId: [{ required: true, message: "请选择城市", trigger: "blur" }],
        validityTime: [
          { required: true, message: "请选择起止日期", trigger: "blur" }
        ],
        serviceFee: [
          { required: true, message: "请选择计提金额", trigger: "blur" }
        ]
      },
      copyRules: {
        cityIds: [{ required: true, message: "请选择城市", trigger: "blur" }]
      }
    };
  },
  created() {
    this.goodsId = this.$route.query.id;
    listAllCity().then(res => {
      this.citys = res.data.data;
    });
    getProduct({ goodsId: this.goodsId }).then(res => {
      this.productList = res.data.data;
    });

    this.getList();
  },
  methods: {
    getAllProduct() {
      getProduct({ goodsId: this.goodsId }).then(res => {
        this.productList = res.data.data;
      });
    },
    getList() {
      this.listLoading = true;
      getFeeList({ cityId: this.listQuery.cityId, goodsId: this.goodsId })
        .then(response => {
          this.list = response.data.data;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    formatTime(time) {
      if (time == null || time === "") {
        return "";
      }
      const date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    handleCreate() {
      this.diaType = "add";
      this.feeDiaVisible = true;
      this.dataForm = {
        productId: "",
        citys: "",
        validityTime: [],
        serviceFee: ""
      };
    },
    handleEdit(row) {
      this.diaType = "edit";
      this.dataForm = row;
      this.dataForm.validityTime = [row.validityStart, row.validityEnd];
      this.feeDiaVisible = true;
    },
    handleDel(row) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteFee({ id: row.id })
          .then(response => {
            this.$notify.success({
              title: "成功",
              message: "删除成功"
            });
            this.getList();
          })
          .catch(response => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg
            });
          });
      });
    },
    confServiceFee() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          let params = {
            goodsId: this.goodsId,
            cityId: this.dataForm.cityId,
            productId: this.dataForm.productId,
            validityStart: this.dataForm.validityTime[0],
            validityEnd: this.dataForm.validityTime[1],
            serviceFee: this.dataForm.serviceFee,
            remark: this.dataForm.remark
          };
          if (this.diaType == "add") {
            addFee(params)
              .then(response => {
                this.feeDiaVisible = false;
                this.$notify.success({
                  title: "成功",
                  message: "创建成功"
                });
                this.getList();
              })
              .catch(response => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg
                });
              });
          } else {
            params.id = this.dataForm.id;
            updateFee(params)
              .then(response => {
                this.feeDiaVisible = false;
                this.$notify.success({
                  title: "成功",
                  message: "编辑成功"
                });
                this.getList();
              })
              .catch(response => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg
                });
              });
          }
        }
      });
    },
    handleCopy(row) {
      this.copyDiaVisible = true;
      this.copyForm.id = row.id;
      this.copyForm.cityIds = [];
    },
    confCopyFee() {
      this.$refs["copyForm"].validate(valid => {
        if (valid) {
          let params = {
            id: this.copyForm.id,
            cityIds: this.copyForm.cityIds
          };

          batchCopy(params)
            .then(response => {
              this.copyDiaVisible = false;
              this.$notify.success({
                title: "成功",
                message: "创建成功"
              });
              this.getList();
            })
            .catch(response => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg
              });
            });
        }
      });
    }
  }
};
</script>

<style>
.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 100px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}

.gallery {
  width: 180px;
  height: 118px;
  margin-right: 10px;
  object-fit: cover;
}

.goods-detail-box img {
  width: 100%;
}

.el-table th.gutter {
  display: table-cell !important;
}
</style>
