<!--  -->
<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel"
                      :content="(payType == 'create' ? '新增服务' : '修改服务')"></el-page-header>
    </h2>
    <div class="m-core" style="overflow: hidden; background-color: #eef4f9; padding: 0;">
      <el-form :model="form"
                ref="accountForm"
                :inline="true"
                label-position="right"
                label-width="120px">
        <div style="background: #fff;padding: 16px 34px 10px;margin-bottom: 20px;">
          <el-alert
            title="服务信息"
            type="info"
            :closable="false"
            class="smallTitle"
          ></el-alert>
          <el-form-item label="服务名称" prop="name" :rules="[{ required: true, message: '请输入服务名称', trigger: 'blur' }]">
            <el-input v-model="form.name" placeholder="请输入服务名称"></el-input>
          </el-form-item>
          <el-form-item label="产品服务" prop="productId" :rules="[{ required: true, message: '请选择产品服务', trigger: 'change' }]">
            <el-select v-model="form.productId" multiple collapse-tags clearable placeholder="请选择产品服务">
              <el-option v-for="(item, index) in productList"
                          :key="index"
                          :label="item.name"
                          :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <div style="background: #fff;padding: 16px 34px 10px;margin-bottom: 20px;">
          <el-alert
            title="服务属性"
            type="info"
            :closable="false"
            class="smallTitle"
          ></el-alert>
          <div class="serviceAttr" v-for="(attrList, index) in form.attrList" :key="index">
            <div class="serviceBlock">
              <el-form-item label="付费模式"
                :prop="'attrList.' + index + '.mode'"
                :rules="[{ required: true, message: '请选择付费模式', trigger: 'change' }]">
                <el-select v-model="attrList.mode" placeholder="请选择付费模式">
                  <el-option label="月" value="MONTH"></el-option>
                  <el-option label="年" value="YEAR"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="add">
                <el-button icon="el-icon-plus" plain style="width: 140px;border-color: #00A79D;color: #00A79D;" @click="onAddItem('child', attrList.attr)">添加模式</el-button>
              </el-form-item>
            </div>
            <div class="serviceBlock">
              <div v-for="(attrItem, i) in attrList.attr" :key="i">
                <el-form-item label="学员上限"
                  :prop="'attrList.' + index + '.attr.' + i + '.studentUpLimit'"
                  :rules="[{ required: true, message: '请输入学员上限', trigger: 'blur' },
                    {type: 'number', message: '学员上限必须为数字值' }]">
                  <el-input v-model.number="attrItem.studentUpLimit" placeholder="请输入学员上限">
                    <span slot="append">人</span>
                  </el-input>
                </el-form-item>
                <el-form-item label="服务原价"
                  :prop="'attrList.' + index + '.attr.' + i + '.originalPrice'"
                  :rules="[{ required: true, message: '请输入服务原价', trigger: 'blur' },
                    {type: 'number', message: '服务原价必须为数字值' }]">
                  <el-input v-model.number="attrItem.originalPrice" placeholder="请输入服务原价">
                    <span slot="append">元</span>
                  </el-input>
                </el-form-item>
                <el-button circle type="text" @click="onRemoveItem(attrList.attr, i)" :disabled="attrList.attr.length <= 1">删除</el-button>
              </div>
            </div>
            <div class="list-remove">
              <el-button type="text"  icon="el-icon-delete" @click="onRemoveItem(form.attrList, index)" :disabled="form.attrList.length <= 1">删除</el-button>
            </div>
          </div>
          <el-form-item class="add" style="margin-top: 18px;    padding-left: 50px;">
            <el-button icon="el-icon-plus" type="primary" style="width: 160px" :disabled="form.attrList.length >= 2" @click="onAddItem('parent')">添加模式</el-button>
          </el-form-item>

          <div class="btn-group">
            <el-button @click="onCancel" >取 消</el-button>
            <el-button type="primary"  @click="onSubmit('accountForm')">确 定</el-button>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { platformProductQueryPage } from '../productManger/api'
import { platformServeAdd, platformServeUpdate, platformServeQueryInfo } from './api'
export default {
  name: 'serviceManger',
  data () {
    const query = this.$route.query
    return {
      payType: query.type,
      productList: [],
      form: {
        attrList: [{
          mode: null,
          attr: [{
            originalPrice: null,
            studentUpLimit: null,
          }]
        }],
        name: null,
        productId: [],
        id: query.id || null
      }
    };
  },
  mounted () {
    this.__init()
  },
  methods: {
    async __init () {
      try {
        const res = await platformProductQueryPage({ page: 1, rows: 999 })
        this.productList = res.data?.rows || []
        if (this.payType == 'update') {
          const queryInfo = await platformServeQueryInfo({ id: this.form.id })
          console.log(queryInfo)
          const result = queryInfo.data || null
          if(result) {
            this.form.productId = result.productId.split(',').map(i => Number(i)),
            this.form.name = result.name,
            this.form.attrList = this.formatAttr(result.detailList, 'asc')
          }
        }
      } catch(e) {}
    },
    onAddItem(type, row) {
      // 添加子项目
      if(type == 'child') {
        row.push({
          mode: null,
          originalPrice: null,
          studentUpLimit: null,
        })
      } else if(type == 'parent') {
        this.form.attrList.push({
          mode: null,
          attr: [{
            originalPrice: null,
            studentUpLimit: null,
          }]
        })
      }
    },
    onRemoveItem(row, index) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then( async() => {
        row.splice(index, 1)
      });
    },
    async onSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const { attrList, productId, ...res } = this.form
          let isYear = 0, isMonth = 0
          attrList.forEach(attr => {
            if(attr.mode == 'YEAR') {
              isYear++
            } else if(attr.mode == 'MONTH') {
              isMonth ++
            }
          })
          if(isYear > 1 || isMonth > 1) {
            this.$message.error('付费模式重复')
            return
          }
          const params = {
            ...res,
            productId: productId.join(','),
            detailList: this.formatAttr(attrList)
          }
          if (this.payType == 'create') {
            platformServeAdd(params).then(res => {
              if (res.code == 200) {
                this.$message.success('保存成功')
                this.onCancel()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else if (this.payType == 'update') {
            platformServeUpdate(params).then(res => {
              if (res.code == 200) {
                this.$message.success('保存成功')
                this.onCancel()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          this.$nextTick(() => {
            let isError = document.getElementsByClassName('is-error')
            isError[0].scrollIntoView({
              block: 'center',
              behavior: 'smooth',
            })
          })
          return false;
        }
      });
    },
    formatAttr(row, type) { // 格式化数据
      let resultArray = []
      if(!row) return
      if(type == 'asc') { // 修改时获取数据重新拼装数据
        let isType = []
        row.forEach(ele => {
          if(isType.includes(ele.mode)) {
            resultArray.forEach(arr => {
              if(arr.mode == ele.mode) {
                arr.attr.push({
                  originalPrice: ele.originalPrice,
                  studentUpLimit: ele.studentUpLimit
                })
              }
            })
          } else {
            isType.push(ele.mode)
            resultArray.push({
              mode: ele.mode,
              attr: [{
                originalPrice: ele.originalPrice,
                studentUpLimit: ele.studentUpLimit
              }]
            })
          }
        });
      } else {
        for(let item of row) {
          if(item.attr && item.attr.length > 0) {
            for(let child of item.attr) {
              resultArray.push({
                mode: item.mode,
                originalPrice: child.originalPrice,
                studentUpLimit: child.studentUpLimit
              })
            }
          }
        }
      }
      return resultArray
    },
    onCancel () {
      this.$store.dispatch('delVisitedViews', this.$route)
      this.$router.push({
        path: "/serviceManager/serviceList"
      });
    }
  },
};
</script>
<style lang='scss' scoped>
.serviceAttr {
  position: relative;
  margin-top: 18px;
  padding-top: 18px;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
}
.list-remove {
  position: absolute;
  right: 20px;
  top: 18px;
  .el-button--text {
    font-size: 18px;
    color: #F56C6C;
    &.is-disabled {
      color: #C0C4CC;
    }
  }
}
.el-select, .el-input {
  width: 200px !important;
}

.btn-group {
  text-align: center;
  padding-bottom: 20px;
}

.smallTitle {
  background: #fff;
  border-bottom: 1px solid #E8E8E8;
  margin-bottom: 20px;
  padding-bottom: 15px;
  color: #393F3E;
  padding-left: 0;
  &::before {
    content: ' ';
    display: inline-block;
    height: 16px;
    width: 3px;
    border-radius: 2px;
    background-color: var(--color-primary);
  }
  /deep/.el-alert__title {
    font-size: 16px !important;
  }
}


</style>
