<template>
  <section class="add_order">
    <ai-detail>
      <template slot="title">
        <ai-title :title="title" isShowBack :isShowBottomBorder="true" @onBackClick="$emit('goBack')"></ai-title>
      </template>
      <template slot="content" v-if="!isEdit">
        <ai-card title="商品信息">
          <template #content>
            <div class="form_div">
              <el-form
                  ref="rules"
                  :model="forms"
                  :rules="formRules"
                  size="small"
                  label-suffix="："
                  label-width="100px">
                <el-form-item label="店铺名称" prop="shopId">
                  <el-select
                      v-model="forms.shopId"
                      placeholder="请选择..."
                      clearable>
                    <el-option
                        v-for="(item, i) in shopList"
                        :key="i"
                        :label="item.shopName"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="商品类型" prop="merchandiseType">
                  <el-select
                      v-model="forms.merchandiseType"
                      placeholder="请选择..."
                      clearable>
                    <el-option
                        v-for="(item, i) in dict.getDict('integralMerchandiseType')"
                        :key="i"
                        :label="item.dictName"
                        :value="item.dictValue">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="商品名称" prop="merchandiseName">
                  <el-input
                      v-model="forms.merchandiseName"
                      placeholder="请输入..."
                      maxlength="100"
                      show-word-limit>
                  </el-input>
                </el-form-item>
                <div class="above">
                  <div class="left">
                    <el-form-item label="单价" prop="costIntegral">
                      <el-input v-model="forms.costIntegral" placeholder="请输入..."/>
                    </el-form-item>
                  </div>
                  <div class="right">
                    <el-form-item label="库存" prop="inventoryNumber">
                      <el-input
                          v-model="forms.inventoryNumber"
                          placeholder="请输入...">
                      </el-input>
                    </el-form-item>
                  </div>
                </div>
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="forms.status">
                    <el-radio label="1">上架中</el-radio>
                    <el-radio label="0">已下架</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="商品图片" prop="fileList" ref="fileList">
                  <div class="upload">
                    <ai-uploader
                        :instance="instance"
                        @change="changeFile"
                        v-model="forms.fileList"
                        :limit="9">
                    </ai-uploader>
                  </div>
                </el-form-item>
                <el-form-item label="商品详情" prop="description">
                  <el-input
                      v-model="forms.description"
                      type="textarea"
                      :rows="5"
                      maxlength="100"
                      show-word-limit
                      placeholder="请输入...">
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
          </template>
        </ai-card>
      </template>
      <template slot="content" v-if="isEdit">
        <ai-card title="商品信息">
          <template #content>
            <div class="info">
              <ai-wrapper label-width="70px" :columnsNumber="1">
                <ai-info-item label="店铺名称"><span>{{ forms.shopName }}</span></ai-info-item>
                <ai-info-item label="商品类型"
                ><span>{{
                    dict.getLabel("integralMerchandiseType", forms.merchandiseType)
                  }}</span></ai-info-item
                >
                <ai-info-item label="商品名称"
                ><span>{{ forms.merchandiseName }}</span></ai-info-item
                >
              </ai-wrapper>
              <ai-wrapper label-width="70px" :columnsNumber="2">
                <ai-info-item label="单价"><span>{{ forms.costIntegral + "积分" }}</span></ai-info-item>
                <ai-info-item label="库存"
                ><span>{{ forms.inventoryNumber }}</span></ai-info-item
                >
                <ai-info-item label="销量"
                ><span>{{ forms.saleNumber || "0" }}</span></ai-info-item
                >
              </ai-wrapper>
              <ai-wrapper label-width="70px" :columnsNumber="1">
                <ai-info-item label="状态"
                ><span
                    :style="{
                      color: dict.getColor(
                        'integralMerchandiseStatus',
                        forms.status
                      ),
                    }"
                >{{
                    dict.getLabel("integralMerchandiseStatus", forms.status)
                  }}</span
                ></ai-info-item
                >
                <ai-info-item label="商品图片">
                  <ai-uploader
                      :disabled="true"
                      :instance="instance"
                      v-model="forms.fileList"
                      :limit="9"
                  ></ai-uploader>
                </ai-info-item>
                <ai-info-item label="商品详情"
                ><span>{{ forms.description }}</span></ai-info-item
                >
              </ai-wrapper>
            </div>
          </template>
        </ai-card>
      </template>
      <template slot="footer" v-if="!isEdit">
        <el-button @click="$emit('goBack')" style="width: 120px">取消</el-button>
        <el-button type="primary" @click="save('rules')" style="width: 120px">提 交</el-button>
      </template>
    </ai-detail>
  </section>
</template>

<script>
import {mapState} from "vuex";

export default {
  name: "addGoods",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    info: Object,
    areaId: String,
  },
  data() {
    return {
      forms: {
        shopId: "",
        merchandiseType: "",
        merchandiseName: "",
        costIntegral: "",
        inventoryNumber: "",
        status: "",
        fileList: [],
        description: "",
      },
      shopList: [],
      title: "添加商品",
      showEdit: false,
      isEdit: false,
      detailInfo: {},
    };
  },
  computed: {
    ...mapState(["user"]),
    formRules() {
      var integral = (rule, value, callback) => {
        if (value) {
          if (/^[1-9]\d*$/.test(value)) {
            callback();
          } else {
            callback(new Error("请输入正整数"));
          }
        } else {
          callback(new Error("请输入单价"));
        }
      };
      return {
        shopId: [{required: true, message: "请选择店铺", trigger: "change"}],
        merchandiseType: [
          {required: true, message: "请选择商品类型", trigger: "change"},
        ],
        merchandiseName: [
          {required: true, message: "请输入商品名称", trigger: "blur"},
        ],
        inventoryNumber: [
          {required: true, validator: integral, trigger: "blur"},
        ],
        costIntegral: [
          {required: true, pattern: /^\d*[.\d]\d?$/, message: "请输入正数,最多保留一位小数", trigger: "blur"},
        ],
        status: [{required: true, message: "请选择状态", trigger: "change"}],
        fileList: [
          {required: true, message: "请上传商品图片", trigger: "change"},
        ],
      };
    },
  },
  created() {
    let l = Object.keys(this.info).length;
    if (this.info.isAdd) {
      this.showEdit = false;
      if (l > 1) {
        this.title = "修改商品";
        this.getShopList().then(() => {
          this.searchDetail(this.info.id);
        });
      } else {
        this.title = "添加商品";
        this.getShopList();
      }
    } else {
      this.title = "商品详情";
      this.isEdit = true;
      this.showEdit = true;
      this.getShopList().then(() => {
        this.searchDetail(this.info.id);
      });
    }
  },
  methods: {
    getShopList() {
      return new Promise((reslove) => {
        this.instance
        .post(`/app/appvillagerintegralshop/listForOperator`, null, {
          params: {
            size: 100000,
            areaId: this.areaId,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.shopList = res.data.records;
            reslove();
          }
        });
      });
    },
    changeFile() {
      this.$refs.fileList.$emit("el.form.change");
    },
    searchDetail(id) {
      this.instance
      .post(`/app/appvillagerintegralmerchandise/queryDetailById`, null, {
        params: {
          id,
        },
      })
      .then((res) => {
        if (res.code == 0) {
          this.forms = {...res.data};
          let i = this.shopList.findIndex(
              (item) => item.id == this.forms.shopId
          );
          if (i > -1) {
            this.forms.shopName = this.shopList[i].shopName;
          }
        }
      });
    },
    edit() {
      this.isEdit = false;
    },
    save(formName, type) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.instance
          .post(
              `/app/appvillagerintegralmerchandise/addOrUpdate`,
              {
                ...this.forms,
                areaId: this.user.info.areaId,
              },
              null
          )
          .then((res) => {
            if (res.code == 0) {
              this.$message.success("提交成功");
              if (type == "detail") {
                this.isEdit = true;
              } else {
                this.$emit("goBack");
              }
            }
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.add_order {
  height: 100%;

  .form_div {
    padding: 16px 0;
  }

  .above {
    overflow: hidden;
    width: 100%;

    .left {
      width: 50%;
      float: left;
    }

    .right {
      width: 50%;
      float: right;
    }
  }

  .iconEdit,
  .Edit {
    color: #5088ff;
    font-size: 12px;
    cursor: pointer;
    padding-left: 8px;
  }

  .info {
    padding: 16px 0;
  }
}
</style>
