<template>
  <div class="app-container">
    <el-form :model="form" ref="form" :rules="rules" label-width="160px">
      <el-form-item label="服务名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入服务名称" :disabled="$route.query.type == 'show'" maxlength="50" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="服务分类" prop="serviceCategorizeId">
        <el-select v-model="form.serviceCategorizeId" :disabled="$route.query.type == 'show'" placeholder="请选择服务分类" clearable style="width: 100%">
          <el-option v-for="(v, i) in typeList" :key="i" :label="v.name" :value="v.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务图片" prop="image">
        <imageUpload v-model="form.image" unique="image" :disabled="$route.query.type == 'show'" :limit="1" />
      </el-form-item>
      <h3>销售信息</h3>
      <el-form-item label="销售价" prop="sellingPrice">
        <el-input-number v-model="form.sellingPrice" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :max="Number(form.originalPrice)||Infinity" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="原价" prop="originalPrice">
        <el-input-number v-model="form.originalPrice" :disabled="$route.query.type == 'show'" controls-position="right" :min="Number(form.costPrice)||0" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="成本价" prop="costPrice">
        <el-input-number v-model="form.costPrice" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="服务单位" prop="serviceUnit">
        <div class="flex">
          <el-select v-model="form.serviceUnit" :disabled="$route.query.type == 'show'" placeholder="请选择服务单位" clearable style="width: 50%;">
            <el-option v-for="(v, i) in serviceUnitList" :key="i" :label="v.value" :value="v.code" />
          </el-select>
          <el-input-number style="margin-left: 20px;margin-right:10px;" v-model="form.serviceUnitDuration" :disabled="$route.query.type == 'show'" controls-position="right" :min="0" :max="99" :precision="0"></el-input-number> 小时
        </div>
      </el-form-item>

      <h3>服务说明</h3>
      <el-form-item label="服务说明" prop="serviceDescription">
        <el-input type="textarea" v-model="form.serviceDescription" :disabled="$route.query.type == 'show'" placeholder="请输入服务说明" clearable />
      </el-form-item>
      <el-form-item label="服务须知" prop="serviceNotice">
        <el-input type="textarea" :rows="2" placeholder="请输入服务须知" :disabled="$route.query.type == 'show'" clearable v-model="form.serviceNotice">
        </el-input>
      </el-form-item>
      <el-form-item label="上架状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" :disabled="$route.query.type == 'show'" style="width: 240px">
          <el-option label="上架" :value="true" />
          <el-option label="下架" :value="false" />
        </el-select>
      </el-form-item>
    </el-form>
    <el-form label-width="120px">
      <el-form-item label="">
        <el-button v-if="$route.query.type != 'show'" :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { businessList, businessProductCategoryList } from "@/api/service";
import {
  serviceProductAdd,
  serviceCategorizeList,
  serviceProductEnum,
  serviceProductInfo,
  serviceProductEdit
} from "@/api/service";
import draggable from "vuedraggable";
export default {
  components: {
    draggable,
  },
  data () {
    return {
      form: {
        name: undefined,
        serviceCategorizeId: undefined,
        image: undefined,
        sellingPrice: undefined,
        originalPrice: undefined,
        costPrice: undefined,
        serviceUnit: undefined,
        serviceDescription: undefined,
        serviceNotice: undefined,
        status: true
      },
      typeList: [],
      rules: {
        name: [
          { required: true, message: "请输入服务名称", trigger: "change" },
        ],
        sellingPrice: [
          { required: true, message: "请输入销售价", trigger: "change" },
        ],
        originalPrice: [
          { required: true, message: "请输入原价", trigger: "change" },
        ],
        costPrice: [
          { required: true, message: "请输入成本价", trigger: "change" },
        ],
        serviceUnit: [
          { required: true, message: "请选择服务单位", trigger: "change" },
        ],
        serviceDescription: [{ required: true, message: "请输入服务说明", trigger: "change" }],
      },
      buttonLoading: false,
      currentDate: new Date(),
      selectedDates: [],
      serviceUnitList: []
    };
  },
  created () {
    this.getTypeList();
    this.getServiceUnitList()
    if (this.$route.query.id) {
      this.getDetails(this.$route.query.id);
    }
  },
  methods: {
    // 判断某个日期是否已被选中
    isSelected (date) {
      return this.selectedDates.some(
        d => d === this.formatDate(date)
      );
    },
    // 获取服务单位列表
    getServiceUnitList () {
      serviceProductEnum().then(res => {
        this.serviceUnitList = res.data.serviceUnit
      })
    },
    // 点击切换选中状态
    toggleSelection (date) {
      if (this.$route.query.type == 'show') return
      let dateString = this.formatDate(date);
      let index = this.selectedDates.findIndex(
        d => this.formatDate(d) === dateString
      );
      if (index === -1) {
        this.selectedDates.push(this.formatDate(date));
      } else {
        this.selectedDates.splice(index, 1);
      }
    },
    // 格式化日期为 YYYY-MM-DD
    formatDate (date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    getDetails (id) {
      serviceProductInfo(id).then((res) => {
        this.form = res.data;
      });
    },
    getTypeList () {
      serviceCategorizeList().then((res) => {
        this.typeList = res.data;
      });
    },
    addBusinessProductCategory () {
      this.form.businessProductTimeList.push({})
    },
    deleteBusinessProductCategory (index) {
      this.form.businessProductTimeList.splice(index, 1)
    },
    cancel () {
      if (this.$route.query.queryParams) {
        localStorage.setItem('queryParams', this.$route.query.queryParams)
      }
      this.$router.go(-1);
    },
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!this.form.serviceUnitDuration) {
            this.$message.error('请输入服务单位时长');
            return
          }
          let formCopy = JSON.parse(JSON.stringify(this.form));
          this.buttonLoading = true;
          if (this.form.id != null) {
            serviceProductEdit(formCopy)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.cancel();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            serviceProductAdd(formCopy)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.cancel();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    addItem () {
      this.form.businessProductNotesList.push({});
    },
    deleteItem (index) {
      this.form.businessProductNotesList.splice(index, 1);
    },
  },
};
</script>

<style lang='scss' scoped>
.el-form {
  width: 1000px;
}
.hint {
  font-size: 12px;
  color: red;
}
.map-box {
  width: calc(100% - 120px);
  height: 300px;
  margin-bottom: 30px;
  box-sizing: border-box;
  margin-left: 120px;
}
.flex {
  display: flex;
  margin-bottom: 10px;
  .el-button {
    margin-left: 10px;
  }
}
h3 {
  width: 160px;
  font-weight: 700;
  text-align: right;
}
.flex-bet {
  display: flex;
  justify-content: space-between;
}
.showTip {
  display: inline-block;
  margin-left: 20px;
  font-weight: 700;
  color: #606266;
}

// .selected {
//   background-color: #909399;
//   color: white;
//   border-radius: 4px;
// }
::v-deep .el-calendar-table .el-calendar-day {
  height: 47px !important;
}
// ::v-deep .el-input.is-disabled .el-input__inner,
// ::v-deep .el-range-editor.is-disabled,
// ::v-deep .el-range-editor.is-disabled input,
// ::v-deep .el-textarea.is-disabled .el-textarea__inner {
//   background-color: #fff;
//   color: rgb(96, 98, 102);
// }
</style>