<template>
  <div id="pricePeriod">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="商品标准价格(元)" prop="standPrice">
          <el-input-number
            :controls="false"
            :min="0"
            :style="`max-width:${inputWidth}px;`"
            v-model="listData.standPrice"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品最低价格(元)" prop="lowestPrice">
          <el-input-number
            :controls="false"
            :min="0"
            :style="`max-width:${inputWidth}px;`"
            v-model="listData.lowestPrice"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品划线价(元)" prop="linePrice">
          <el-input-number
            :controls="false"
            :min="0"
            :style="`max-width:${inputWidth}px;`"
            v-model="listData.linePrice"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="listData.status">
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="在选品中心显示">
          <el-radio-group
            v-model="listData.showStatus"
            @change="listData.centerShowNum = ''"
          >
            <el-radio :label="1">是</el-radio>
            <el-input
              :maxlength="9"
              v-if="listData.showStatus"
              style="width: 110px; margin-right: 30px"
              onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
              v-model.number="listData.showSort"
              placeholder="排序"
            ></el-input>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品有效期" prop="timeArrays">
          <el-date-picker
            v-model="listData.timeArrays"
            type="datetimerange"
            value-format="timestamp"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changeDataTime(listData.timeArrays)"
          >
          </el-date-picker>
          <el-tooltip class="item" effect="dark" placement="right">
            <div slot="content">
              商品有效期：商品可以进行售卖的有效时间范围<br />
              1.非时间范围，不可以上架进行售卖；<br />
              2.到了结束日期，不需要人为操作，系统自动下架商品
            </div>
            <i
              style="margin-left: 10px; font-size: 20px; color: #e6a23c"
              class="el-icon-warning"
            ></i>
          </el-tooltip>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label=" " prop="standPriceJson" label-width="0px">
          <h5 style="margin: 0px">
            商品标准价格明细表：
            <el-button type="text" @click="addPriceInfo">添加</el-button>
          </h5>
          <el-table
            :data="listData.standPriceJson"
            show-summary
            :summary-method="totalPrice"
            border
            :header-cell-style="{
              'background-color': '#eee',
              padding: '8px',
              color: '#333',
            }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            >
            </el-table-column>
            <el-table-column
              v-for="(item, index) in tableSet"
              :width="item.width"
              :key="index"
              :label="item.label"
              align="center"
              :show-overflow-tooltip="true"
              header-align="center"
              :prop="item.prop"
            >
              <template slot-scope="scope">
                <span
                  v-if="item.scope === 'editInfo'"
                  @click="editPriceInfo(scope.row)"
                  class="clickSpan"
                  >{{ scope.row[item.prop] }}</span
                >
                <span v-else-if="item.scope === 'leftCh'"
                  >{{ item.ch }}{{ scope.row[item.prop] }}</span
                >
                <span v-else>{{ scope.row[item.prop] }}</span></template
              >
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="100px"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="delPriceInfo(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 费用类型 -->
    <el-dialog
      @open="openFunc"
      :visible.sync="dialogVisible"
      width="500px"
      :show-close="false"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">{{ popupStatus === 1 ? "添加" : "编辑" }}</div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Close@2x.png"
            alt=""
            @click="dialogVisible = false"
          />
        </div>
      </div>
      <el-form
        label-position="right"
        label-width="110px"
        :model="priceDetails"
        :rules="rulesItem"
        ref="priceDetails"
      >
        <el-form-item
          v-for="(items, indexs) in priceDetailsList"
          :key="indexs"
          :label="items.label"
          :prop="items.prop"
        >
          <el-select
            v-if="items.scope === 'select'"
            v-model="priceDetails[items.prop]"
            placeholder="请选择费用类型"
          >
            <el-option
              v-for="(item, index) in paycost"
              :key="index"
              :label="item.costName"
              :value="item.costId"
            >
            </el-option>
          </el-select>
          <el-input v-else v-model="priceDetails[items.prop]"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('priceDetails')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  props: ["listData"],
  data() {
    return {
      inputWidth: 217,
      tableSet: [
        {
          label: "费用类型",
          prop: "priceTypeName",
          prop1: "priceTypeId",
          scope: "editInfo",
        },
        {
          label: "费用金额（元）",
          prop: "price",
          scope: "leftCh",
          ch: "￥",
        },
      ],
      // 弹窗字段
      priceDetailsList: [
        {
          label: "费用类型",
          prop: "priceTypeId",
          scope: "select",
          options: [],
        },
        {
          label: "费用金额",
          prop: "price",
        },
      ],
      priceInfoIndex: null, //当前编辑价格明细内容位置
      popupStatus: null,
      dialogVisible: false,
      priceDetails: {},
      rulesItem: {
        priceTypeId: [
          {
            required: true,
            message: "请选择费用类型",
            trigger: ["blur", "change"],
          },
        ],
        price: [
          { required: true, message: "请输入费用金额", trigger: "blur" },
          {
            validator(rule, value, callback) {
              var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入不超过两位小数点的价格数值"));
              }
            },
            trigger: "blur",
          },
        ],
      }, //表单验证
    };
  },
  computed: { ...mapGetters(["paysupply", "educationType", "paycost"]) },
  methods: {
    changeDataTime() {
      if (
        this.listData.studyTimeArrays &&
        this.listData.studyTimeArrays.length
      ) {
        this.$bus.$emit("againValidate");
      }
    },
    openFunc() {
      if (this.$refs.priceDetails) {
        this.$nextTick(() => {
          this.$refs.priceDetails.clearValidate();
        });
      }
    },
    /**
     * 新增价格明细条
     */
    addPriceInfo() {
      this.priceDetails = {};
      this.popupStatus = 1;
      this.dialogVisible = true;
    },
    /**
     * 修改价格明细条
     */
    editPriceInfo(row) {
      this.priceInfoIndex = this.listData.standPriceJson.indexOf(row);
      this.priceDetails = JSON.parse(JSON.stringify(row));
      this.popupStatus = 2;
      this.dialogVisible = true;
    },
    /**
     * 删除价格明细条
     */
    delPriceInfo(row) {
      this.listData.standPriceJson.splice(
        this.listData.standPriceJson.indexOf(row),
        1
      );
      this.$bus.$emit("checkStandPriceJson");
    },
    /**
     * 价格明细表-总价计算
     */
    totalPrice(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = "￥" + sums[index];
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    /**
     * 价格明细表-表单验证
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.rulesTable();
        } else {
          return false;
        }
      });
    },
    /**
     * 价格明细表-提交API
     */
    rulesTable() {
      if (this.popupStatus === 2) {
        this.$set(
          this.listData.standPriceJson,
          this.priceInfoIndex,
          this.priceDetails
        );
      } else {
        if (this.listData.standPriceJson) {
          const repeatCheck = this.listData.standPriceJson.some((item) => {
            return item.priceTypeId === this.priceDetails.priceTypeId;
          });
          if (repeatCheck) {
            this.$message.warning("已存在相同费用类型，禁止重复");
            return;
          }
        } else {
          this.$set(this.listData, "standPriceJson", []);
        }
        for (let i = 0; i < this.paycost.length; i++) {
          if (
            this.paycost[i].costId === Number(this.priceDetails.priceTypeId)
          ) {
            this.priceDetails.priceTypeName = this.paycost[i].costName;
            break;
          }
        }
        this.listData.standPriceJson.push(this.priceDetails);
        this.$bus.$emit("checkStandPriceJson");
      }
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
</style>
