<template>
  <div class='main-content'>
    <baseTable
      ref='WishingTree'
      :tableHeader='tableHeader'
      :tableData='tableData'
      :searchParams='searchParams'
      @searchFn='searchFn'
      @resetFn='resetFn'
      :moreOperation='false'
      @addFn="addFn"
    >
      <template slot='search'>
        <el-form-item label='手机号'>
          <el-input v-model.trim='searchParams.name' />
        </el-form-item>
        <el-form-item label='内容关键字'>
          <el-input v-model.trim='searchParams.discription' />
        </el-form-item>
      </template>
    </baseTable>

    <el-dialog width="900px" :title="formDialog.title" :visible.sync="formDialog.visible" :close-on-click-modal="false">
      <el-form
        ref="userForm"
        size="small"
        label-width="120px"
        :model="formDialog.formData"
        :rules="formDialog.formRules"
      >
        <el-row>
          <el-form-item label="许愿树名称" prop="name">
            <el-input v-model.trim="formDialog.formData.name" />
          </el-form-item>
          <el-form-item label="经度" prop="longitude">
            <el-input v-model.trim="formDialog.formData.longitude" />
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model.trim="formDialog.formData.latitude" />
          </el-form-item>
          <el-form-item label="可许愿半径" prop="radius">
            <el-input type="number" v-model.trim="formDialog.formData.radius" />
          </el-form-item>
          <el-form-item label='封面图片' prop='coverImage'>
            <el-input style="display: none" v-model.trim="formDialog.formData.coverImage" />
            <el-upload
              class="avatar-uploader"
              :action="upload.action"
              :headers="upload.headers"
              :show-file-list="false"
              :on-success="handleSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="许愿树描述" prop="description">
            <el-input type='textarea' v-model.trim='formDialog.formData.description' :rows='4' />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="formDialog.loading" @click="submitFn">确定</el-button>
        <el-button @click="cancelFn">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { creatTree, queryTreePage } from '@api/wishing/tree';
import { removeUser, updateUserDetail } from '@api/upms/api-user';
import { isNumber, isInteger } from '@utils/validate';

export default {
  name: 'WishingTree',

  data() {
    let validateNumber = (rule, value, callback) => {
      if (!isNumber(value)) {
        return callback(new Error('经纬度只能是数字'));
      } else {
        return callback();
      }
    };

    let validateInteger = (rule, value, callback) => {
      if (!isInteger(value)) {
        return callback(new Error('可许愿半径只能是整数'));
      } else {
        return callback();
      }
    };

    return {
      tableHeader: [
        {
          label: '许愿树名称',
          prop: 'name',
          align: 'center'
        },
        {
          label: '经度',
          prop: 'longitude',
          align: 'center'
        },
        {
          label: '维度',
          prop: 'latitude',
          align: 'center'
        },
        {
          label: '地址',
          prop: 'address',
          align: 'center'
        },
        {
          label: '封面图片',
          prop: 'coverImage',
          align: 'center'
        },
        {
          label: '是否启动',
          prop: 'isActive',
          align: 'center'
        },
        {
          label: '可许愿半径',
          prop: 'radius',
          align: 'center'
        },
        {
          label: '许愿次数',
          prop: 'totalWishes',
          align: 'center',
          type: 'render',
          render: (h, params) => {
            return h('span', params.row.totalWishes || 0);
          }
        },
        {
          label: '创建时间',
          prop: 'createdAt',
          align: 'center'
        }
      ],
      tableData: [],
      defaultSearch: {},
      searchParams: Object.assign({}, this.$search),
      upload: {
        headers: { Authorization: `Bearer ${this.$store.getters.accessToken}` },
        action: '/dgapi/upms/attachment/upload-file',
        extraData: {}
      },
      imageUrl: '',
      formDialog: {
        title: '',
        visible: false,
        loading: false,
        isAdd: false,
        formData: {
          id: 0,
          address: '',
          coverImage: '',
          description: '',
          latitude: null,
          longitude: null,
          name: '',
          radius: 100,
          totalWishes: 0
        },
        formRules: {
          name: [
            {
              required: true,
              message: '请输入许愿树名称',
              trigger: 'blur'
            }
          ],
          latitude: [
            {
              required: true,
              message: '请输入纬度',
              trigger: 'blur'
            },
            {
              validator: validateNumber,
              trigger: 'blur'
            }
          ],
          longitude: [
            {
              required: true,
              message: '请输入经度',
              trigger: 'blur'
            },
            {
              validator: validateNumber,
              trigger: 'blur'
            }
          ],
          radius: [
            {
              validator: validateInteger,
              trigger: 'blur'
            }
          ]
        }
      }
    };
  },
  created() {
    this.searchFn();
  },
  mounted() {

  },
  methods: {
    searchFn(isReset = false) {
      let vm = this;
      if (isReset) {
        vm.searchParams = Object.assign(vm.searchParams, vm.$search);
      }
      queryTreePage(vm.searchParams).then(
        (res) => {
          vm.tableData = res.data.records;
          vm.searchParams.total = res.data.total;
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    resetFn() {
      let vm = this;
      vm.searchParams = Object.assign({}, vm.defaultSearch, this.$search);
      vm.searchFn();
    },
    addFn() {
      let vm = this;
      vm.formDialog.title = '新增';
      vm.formDialog.visible = true;
      vm.formDialog.loading = false;
      vm.formDialog.isAdd = true;
      vm.formDialog.formData = {};
    },
    cancelFn() {
      let vm = this;
      vm.formDialog.visible = false;
      vm.formDialog.loading = false;
      vm.formDialog.isAdd = false;
      vm.formDialog.formData = {};
      vm.$refs.userForm.resetFields();
    },
    submitFn() {
      let vm = this;
      vm.formDialog.loading = true;
      if (!vm.formDialog.formData.coverImage || vm.formDialog.formData.coverImage === '') {
        vm.$message.error('请上传封面图片');
        vm.formDialog.loading = false;
        return;
      }
      vm.$refs.userForm.validate((valid) => {
        if (!valid) {
          vm.formDialog.loading = false;
          return;
        }
        if (this.formDialog.formData.id) {
          let formData = vm.formDialog.formData;
          updateUserDetail(formData).then(
            (res) => {
              vm.$message.success('修改成功');
              vm.formDialog.visible = false;
              vm.formDialog.loading = false;
              vm.searchFn(true);
            },
            (error) => {
              vm.$notify.error({
                title: error.data.msg,
                message: error.data.data
              });
              vm.formDialog.loading = false;
            }
          );
        } else {
          let formData = vm.formDialog.formData;
          creatTree(formData).then(
            (res) => {
              vm.$message.success('新增成功');
              vm.formDialog.visible = false;
              vm.formDialog.loading = false;
              vm.formDialog.formData = {};
              vm.searchFn(true);
            },
            (error) => {
              vm.$notify.error({
                title: error.data.msg,
                message: error.data.data
              });
              vm.formDialog.loading = false;
            }
          );
        }
      });
    },
    delFn(row) {
      let vm = this;
      vm.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        let ids = [row.id];
        removeUser({ ids: ids }).then(
          (res) => {
            vm.$message.success('删除成功');
            vm.searchFn(true);
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          }
        );
      });
    },
    handleSuccess(res, file, fileList) {
      if (res.code === 200) {
        this.imageUrl = res.data.url;
        this.formDialog.formData.coverImage = res.data.url;
      } else {
        this.$message.error(res.msg);
      }
    }
  }
};
</script>

<style scoped type="less">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 2px dashed #d9d9d9;
}
</style>
