<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      云教练收费标准
    </h2>
    <div class="m-core"  v-if="(tableList.length>0 || rules.page>1)&&contextFlag">
      <save-form
        :inline="true"
        class="searchForm"
        save-key="memberFeeSet"
        ref="searchForm"
        @submit="search"
        @reset="onReSet"
        :model.sync="searchForm"
      >
        <!-- 状态 指导老师 活动方案-->
        <el-form-item prop="search">
          <el-input
            v-model.trim="searchForm.search"
            clearable
            placeholder="云教练名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select
            class="multiple"
            filterable
            style="width: 180px !important"
            v-model.trim="searchForm.organId"
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
          <el-button native-type="reset" type="primary">重置</el-button>
        </el-form-item>
      </save-form>
      <el-button
        type="primary"
        style="margin-bottom: 20px"
        v-permission="'memberRankOrganizationFeeMapper/add'"
        @click="addFee"
        >新增收费标准</el-button
      >
      <el-table
        :data="tableList"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
      >
        <el-table-column
          align="left"
          prop="organName"
          label="分部"
        ></el-table-column>
        <el-table-column
          align="left"
          prop="rankName"
          label="云教练名称"
        ></el-table-column>
        <!-- <el-table-column align="center" prop="type" label="1天收费现价（元）">
        <template slot-scope="scope">
          <div>
            {{ scope.row.memberFeeSetting.currentDayFee | hasMoneyFormat }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="type" label="1天收费原价（元）">
        <template slot-scope="scope">
          <div>
            {{ scope.row.memberFeeSetting.originalDayFee | hasMoneyFormat }}
          </div>
        </template>
      </el-table-column> -->
        <el-table-column align="left" prop="type" label="月收费">
          <template slot-scope="scope">
            <div>
              <p>
                团购:
                {{
                  scope.row.memberFeeSetting.groupPurchaseMonthFee
                    | hasMoneyFormat
                }}
              </p>
              <!-- <p>
              零售:
              {{ scope.row.memberFeeSetting.currentMonthFee | hasMoneyFormat }}
            </p> -->
              <p>
                原价:
                {{
                  scope.row.memberFeeSetting.originalMonthFee | hasMoneyFormat
                }}
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="type" label="季度收费">
          <template slot-scope="scope">
            <div>
              <p>
                团购:
                {{
                  scope.row.memberFeeSetting.groupPurchaseQuarterlyFee
                    | hasMoneyFormat
                }}
              </p>
              <!-- <p>
              零售:
              {{
                scope.row.memberFeeSetting.currentQuarterlyFee | hasMoneyFormat
              }}
            </p> -->
              <p>
                原价:
                {{
                  scope.row.memberFeeSetting.originalQuarterlyFee
                    | hasMoneyFormat
                }}
              </p>

              <!-- </div>
            {{ scope.row.memberFeeSetting.currentHalfYearFee | hasMoneyFormat }} -->
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="type" label="半年收费">
          <template slot-scope="scope">
            <div>
              <p>
                团购:
                {{
                  scope.row.memberFeeSetting.groupPurchaseHalfYearFee
                    | hasMoneyFormat
                }}
              </p>
              <!-- <p>
              零售:
              {{
                scope.row.memberFeeSetting.currentHalfYearFee | hasMoneyFormat
              }}
            </p> -->
              <p>
                原价:
                {{
                  scope.row.memberFeeSetting.originalHalfYearFee
                    | hasMoneyFormat
                }}
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="type" label="年收费">
          <template slot-scope="scope">
            <div>
              <p>
                团购:
                {{
                  scope.row.memberFeeSetting.groupPurchaseYearFee
                    | hasMoneyFormat
                }}
              </p>
              <!-- <p>
              零售:
              {{ scope.row.memberFeeSetting.currentYearFee | hasMoneyFormat }}
            </p> -->
              <p>
                原价:
                {{
                  scope.row.memberFeeSetting.originalYearFee | hasMoneyFormat
                }}
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="100px"
          prop="updateTime"
          label="修改时间"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="operatorName"
          label="修改人"
        ></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <div>
              <!-- memberRankSetting/add -->
              <auth auths="memberRankOrganizationFeeMapper/get">
                <el-button type="text" @click="resetFee(scope.row, 'look')"
                  >详情</el-button
                >
              </auth>
              <auth :auths="'memberRankOrganizationFeeMapper/update'">
                <el-button type="text" @click="resetFee(scope.row, 'update')"
                  >修改</el-button
                >
              </auth>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        save-key="memberFeeSet"
        :total.sync="rules.total"
        sync
        :page.sync="rules.page"
        :limit.sync="rules.limit"
        :page-sizes="rules.page_size"
        @pagination="getList"
      />
    </div>
    <emptyPage @submit="addFee" title='云教练收费标准' btnTitle='新建云教练收费标准' :context='context' v-if="!(tableList.length>0 || rules.page>1)&&contextFlag" />
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="branchStatus"
      v-if="branchStatus"
      default-expand-all
      @close="onFormClose('ruleForm')"
      width="730px"
    >
      <el-form :model="form" :inline="true" ref="ruleForm">
        <el-form-item
          label="所属分部"
          prop="organId"
          :rules="[{ required: true, message: '请选择分部' }]"
          :label-width="formLabelWidth"
        >
          <el-select
            :disabled="addDisabled"
            class="multiple"
            filterable
            style="width: 545px !important"
            v-model.trim="form.organId"
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="云教练名称"
          prop="memberRankSettingId"
          :rules="[{ required: true, message: '请选择云教练' }]"
          :label-width="formLabelWidth"
        >
            <!-- :disabled="addDisabled" -->
          <el-select
            disabled
            class="multiple"
            filterable
            style="width: 545px !important"
            v-model.trim="form.memberRankSettingId"
            clearable
            placeholder="请选择云教练"
          >
            <el-option
              v-for="(item, index) in remberList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          prop="groupPurchaseDayFee"
          label="日收费团购价"
          :rules="[
            { required: true, message: '请输入日收费团购价' },
            {
              pattern:
                /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确的金额',
            },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.groupPurchaseDayFee"
            :disabled="addDisabled"
            class="feeInput"
          >
            <template slot="append">元/日</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="currentDayFee"
          label="日收费零售价"
          :rules="[
            {
              required: true,
              message: '请输入日收费零售价',
              trigger: 'blur, change',
            },
            {
              pattern:
                /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确的金额',
            },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.currentDayFee"
            :disabled="addDisabled"
            class="feeInput"
          >
            <template slot="append">元/日</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="originalDayFee"
          label="日收费原价"
          :rules="[
            { required: true, message: '请输入日收费原价' },
            {
              pattern:
                /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确的金额',
            },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.originalDayFee"
            :disabled="addDisabled"
            class="feeInput"
          >
            <template slot="append">元/日</template>
          </el-input>
        </el-form-item> -->

        <el-form-item
          prop="groupPurchaseMonthFee"
          label="月收费团购价"
          :rules="[
            { required: true, message: '请输入月收费团购价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateMonth, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
            :placeholder="monthRule"
        >
          <el-input
            v-model="form.groupPurchaseMonthFee"
            :disabled="addDisabled"
            class="feeInput"
            :placeholder="monthRule"
          >
            <template slot="append">元/月</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="currentMonthFee"
          label="月收费零售价"
          :rules="[
            { required: true, message: '请输入月收费零售价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateMonth, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.currentMonthFee"
            :disabled="addDisabled"
            class="feeInput"
                  :placeholder="monthRule"
          >
            <template slot="append">元/月</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="originalMonthFee"
          label="月收费原价"
          :rules="[
            { required: true, message: '请输入月收费原价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateMonth, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.originalMonthFee"
            :disabled="addDisabled"
            class="feeInput"
            :placeholder="monthRule"
          >
            <template slot="append">元/月</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="groupPurchaseQuarterlyFee"
          label="季度收费团购价"
          :rules="[
            { required: true, message: '请输入季度收费团购价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateQuarterly, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.groupPurchaseQuarterlyFee"
            :disabled="addDisabled"
            class="feeInput"
            :placeholder="quarterlyRule"
          >
            <template slot="append">元/季度</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="currentQuarterlyFee"
          label="季度收费零售价"
          :rules="[
            { required: true, message: '请输入季度收费零售价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateQuarterly, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"

        >
          <el-input
            v-model="form.currentQuarterlyFee"
            :disabled="addDisabled"
            class="feeInput"
             :placeholder="quarterlyRule"
          >
            <template slot="append">元/季度</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="originalQuarterlyFee"
          label="季度收费原价"
          :rules="[
            { required: true, message: '请输入季度收费原价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateQuarterly, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.originalQuarterlyFee"
            :disabled="addDisabled"
            class="feeInput"
            :placeholder="quarterlyRule"
          >
            <template slot="append">元/季度</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="groupPurchaseHalfYearFee"
          label="半年收费团购价"
          :rules="[
            { required: true, message: '请输入半年收费团购价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateHalfYear, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.groupPurchaseHalfYearFee"
            :disabled="addDisabled"
            class="feeInput"
            :placeholder="halfYearRule"
          >
            <template slot="append">元/半年</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="currentHalfYearFee"
          label="半年收费零售价"
          :rules="[
            { required: true, message: '请输入半年收费零售价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
              { validator: validateHalfYear, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.currentHalfYearFee"
            :disabled="addDisabled"
            class="feeInput"
             :placeholder="halfYearRule"
          >
            <template slot="append">元/半年</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="originalHalfYearFee"
          label="半年收费原价"
          :rules="[
            { required: true, message: '请输入半年收费原价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateHalfYear, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.originalHalfYearFee"
            :disabled="addDisabled"
            class="feeInput"
            :placeholder="halfYearRule"
          >
            <template slot="append">元/半年</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="groupPurchaseYearFee"
          label="年收费团购价"
          :rules="[
            { required: true, message: '请输入年收费团购价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateYear, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.groupPurchaseYearFee"
            :disabled="addDisabled"
            class="feeInput"
            :placeholder="yearRule"
          >
            <template slot="append">元/年</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="currentYearFee"
          label="年收费零售价"
          :rules="[
            { required: true, message: '请输入年收费零售价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
             { validator: validateYear, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.currentYearFee"
            :disabled="addDisabled"
            class="feeInput"
                        :placeholder="yearRule"
          >
            <template slot="append">元/年</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="originalYearFee"
          label="年收费原价"
          :rules="[
            { required: true, message: '请输入年收费原价' },
            {
              pattern: /^[1-9][0-9]*$/,
              message: '请输入大于0的正整数',
            },
            { validator: validateYear, trigger: 'blur' },
          ]"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.originalYearFee"
            :disabled="addDisabled"
            class="feeInput"
            :placeholder="yearRule"
          >
            <template slot="append">元/年</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="!addDisabled" @click="branchStatus = false"
          >取 消</el-button
        >
        <el-button @click="onSubmit" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import numeral from "numeral";
import {
  getAllmemberRank,
  addMemberOrganizationFeeMapper,
  getmemberRankOrganizationFeeMapper,
  getmemberOrganizationFeeMapperkDetail,
  resetMemberOrganizationFeeMapper,
} from "./api";
import { sysConfigList } from "@/api/generalSettings";
import pagination from "@/components/Pagination/index";
import emptyPage from '@/components/emptyPage'
// numeral(this.list.form[index].courseTotalMinuties * this.list.form[index].unitPrice).format('0,0.00')
export default {
  components: { pagination,emptyPage },
  name: "memberFeeSet",
  data() {
    return {
      searchForm: {
        search: null,
        organId: null,
      },
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      tableList: [],
      addDisabled: false,
      title: "新增收费标准",
      pageType: 'create',
      formLabelWidth: "120px",
      form: {
        currentDayFee: "",
        currentHalfYearFee: "",
        currentMonthFee: "",
        currentYearFee: "",
        originalDayFee: "",
        originalHalfYearFee: "",
        originalMonthFee: "",
        originalYearFee: "",
        groupPurchaseDayFee: "",
        groupPurchaseHalfYearFee: "",
        groupPurchaseMonthFee: "",
        groupPurchaseQuarterlyFee: "",
        groupPurchaseYearFee: "",
        organId: "",
        memberRankSettingId: "",
      },
      branchStatus: false,
      remberList: [],
      rulesForm: {
        minMonthFee: null,
        maxMonthFee: null,
        minQuarterlyFee: null,
        maxQuarterlyFee: null,
        minHalfYearFee: null,
        maxHalfYearFee: null,
        minYearFee: null,
        maxYearFee: null,
      },
      context:'云教练收费标准，可根据各分部的实际情况为分部制定不同的售价标准，设置完成后，各分部为学员创建云教练缴费时默认以此处设置的价格向学员收费。',
      contextFlag:false
    };
  },
  async mounted() {
    await this.$store.dispatch("setBranchs");
    // 获取所有的会员
    try {
      const res = await getAllmemberRank();
      this.remberList = res.data;
      // 默认选中第一个
      if(this.pageType == 'create' && this.remberList.length > 0) {
        this.form.memberRankSettingId = this.remberList[0].id
      }
    } catch {}

    this.getList();
    this.getRules();
  },
  methods: {
    async getRules() {
      try {
        const res = await sysConfigList({ group: "DEFAULT" });
        const paramName = "cloud_price_range";
        res.data.forEach((item) => {
          if (item.paramName == paramName) {
            const itemValue = item.paranValue
              ? JSON.parse(item.paranValue)
              : null;
            if (itemValue) {
              this.rulesForm = itemValue;
            }
            // this.$set(this.form, item.id, item.paranValue);
          }
          // this.form[item.paramName] = item.paranValue
          // this.$set(this.form, item.id, item.paranValue);
        });
        // this.$forceUpdate()
        // console.log(this.form);
      } catch (e) {
        console.log(e);
      }
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
      this.$refs.searchForm.resetFields();
      this.search();
    },
    async getList() {
      try {
        const res = await getmemberRankOrganizationFeeMapper({
          ...this.searchForm,
          rows: this.rules.limit,
          page: this.rules.page,
        });
        this.contextFlag = true;
        this.tableList = res.data.rows;
        this.rules.total = res.data.total;
      } catch {}
    },
    onFormClose(ruleForm) {
      (this.form = {
        currentDayFee: "",
        currentHalfYearFee: "",
        currentMonthFee: "",
        currentYearFee: "",
        originalDayFee: "",
        originalHalfYearFee: "",
        originalMonthFee: "",
        originalYearFee: "",
        organId: "",
        memberRankSettingId: "",
      }),
        this.$refs[ruleForm].resetFields();
    },
    addFee() {
      this.title = "新增收费标准";
      this.addDisabled = false;
      this.pageType = "create";
      this.branchStatus = true;
    },
    resetFee(row, type) {
      if (type == "update") {
        this.title = "修改收费标准";
        this.pageType = "update";
        this.addDisabled = false;
      } else {
        this.addDisabled = true;
        this.title = "查看收费标准";
        this.pageType = "look";
      }
      let obj = {};
      for (let key in row.memberFeeSetting) {
        if ((row.memberFeeSetting, key, row.memberFeeSetting[key])) {
          obj[key] = row.memberFeeSetting[key];
        }
      }

      this.form = {
        ...obj,
        organId: row.organId,
        memberRankSettingId: row.memberRankSettingId,
        outId: row.id,
      };
      this.branchStatus = true;
    },
    onSubmit() {
      console.log(this.pageType);
      if (this.pageType == "look") {
        this.branchStatus = false;
        return;
      }
      this.$refs.ruleForm.validate(async (flag) => {
        if (flag) {
          if (this.pageType == "update") {
            try {
              const res = await resetMemberOrganizationFeeMapper({
                memberFeeSetting: { ...this.form },
                organId: this.form.organId,
                memberRankSettingId: this.form.memberRankSettingId,
                id: this.form.outId,
              });
              this.$message.success("修改成功");
              this.branchStatus = false;
              this.getList();
            } catch (e) {
              console.log(e);
            }
          } else if (this.pageType == "create") {
            try {
              const res = await addMemberOrganizationFeeMapper({
                memberFeeSetting: { ...this.form },
                organId: this.form.organId,
                memberRankSettingId: this.form.memberRankSettingId,
              });
              this.$message.success("新建成功");
              this.branchStatus = false;
              this.getList();
            } catch {}
          }
        }
      });
    },
    validateMonth(rule, value, callback) {
      const one = Number(value);
      const min = Number(this.rulesForm.minMonthFee);
      const max = Number(this.rulesForm.maxMonthFee);
      if (one >= min && one <= max) {
        return callback();
      }
      return callback(new Error(`月度云教练定价应在${min}-${max}之间`));
    },
    validateQuarterly(rule, value, callback) {
      const one = Number(value);
      const min = Number(this.rulesForm.minQuarterlyFee);
      const max = Number(this.rulesForm.maxQuarterlyFee);
      if (one >= min && one <= max) {
        return callback();
      }
      return callback(new Error(`季度云教练定价应在${min}-${max}之间`));
    },
    validateHalfYear(rule, value, callback) {
      const one = Number(value);
      const min = Number(this.rulesForm.minHalfYearFee);
      const max = Number(this.rulesForm.maxHalfYearFee);
      if (one >= min && one <= max) {
        return callback();
      }
      return callback(new Error(`半年云教练定价应在${min}-${max}之间`));
    },
    validateYear(rule, value, callback) {
      const one = Number(value);
      const min = Number(this.rulesForm.minYearFee);
      const max = Number(this.rulesForm.maxYearFee);
      if (one >= min && one <= max) {
        return callback();
      }
      return callback(new Error(`年度云教练定价应在${min}-${max}之间`));
    },
  },
  watch: {
    branchStatus(val) {
      if (!val) {
        this.onFormClose("ruleForm");
      }
    },
  },
  computed: {
    monthRule() {
      return `${this.rulesForm.minMonthFee}-${this.rulesForm.maxMonthFee}`;
    },
    quarterlyRule() {
      return `${this.rulesForm.minQuarterlyFee}-${this.rulesForm.maxQuarterlyFee}`;
    },
    halfYearRule() {
      return `${this.rulesForm.minHalfYearFee}-${this.rulesForm.maxHalfYearFee}`;
    },
    yearRule() {
      return `${this.rulesForm.minYearFee}-${this.rulesForm.maxYearFee}`;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-input-group__append {
  width: 88px;
}
.feeInput {
  ::v-deep .el-input__inner {
    width: 120px !important;
  }
}
</style>
