<template>
  <a-spin :spinning="confirmLoading">
    <div class="title-top">
      <h3>{{title}}</h3>
      <div class="button">
        <a-button @click="onCancel">返回</a-button>
        <a-button type="primary" @click="submitForm()" v-if="pageType !== '3'">确认</a-button>
      </div>
    </div>

    <j-form-container :disabled="pageType == '3'">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-card>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="分利规则名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ruleName">
                <a-input v-model="model.ruleName" placeholder="请输入"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="选择合作伙伴" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="partnerName">
                <my-popup
                  v-model="model.partnerName"
                  icon="team"
                  field="name"
                  title="选择合作伙伴"
                  :multi="false"
                  url="/property-central/partners/partnersInfo/list?auditStatus=auditPass"
                  :columns="partnersColumns"
                  @callback="onChosePartners"
                />
              </a-form-model-item>
              <!-- <p style="margin-bottom:0;transform:translate(25%, -23px)">若不选合作伙伴，则商铺未绑定合作伙伴时，合作伙伴不进行分利</p> -->
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="商铺数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shopNum">
                <a-input-group compact>
                  <a-select style="width: 30%" v-model="model.judgingCondition">
                    <a-select-option value=">">{{'>'}}</a-select-option>
                    <!-- <a-select-option value="≤">≤</a-select-option> -->
                  </a-select>
                  <!-- <a-input style="width: 50%" placeholder="商铺数量" v-model="model.shopNum" /> -->
                  <a-input-number
                    v-model="model.shopNum"
                    :min="0"
                    placeholder="商铺数量"
                    style="width:150px"
                  />
                </a-input-group>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="是否限定小区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rangeType">
                <a-radio-group v-model="model.rangeType">
                  <a-radio value="point">指定</a-radio>
                  <a-radio value="all">全部</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
          </a-row>


          <div style="" v-if="model.rangeType === 'point'">
            <!-- 操作按钮区域 -->
            <div class="table-operator">
              <a-button @click="onHandleAddVillage" type="primary" icon="plus">新增</a-button>
            </div>
            <div>
              <a-table ref="table" size="middle" :scroll="{x:true}" bordered rowKey="id" :columns="villageBenefitsColumns" :dataSource="villageDataSource">
                <span slot="saasBenefits" slot-scope="text, record">
                  <a-input-number
                    v-model="record.saasBenefits"
                    :min="0"
                    :max="99"
                    :formatter="value => value ? `${value}%` : ''"
                    :parser="value => value.replace('%', '')"
                    style="width:100%"
                  />
                </span>
                <span slot="partnerBenefits" slot-scope="text, record">
                  <a-input-number
                    v-model="record.partnerBenefits"
                    :min="0"
                    :max="99"
                    :formatter="value => value ? `${value}%` : ''"
                    :parser="value => value.replace('%', '')"
                    style="width:100%"
                  />
                </span>
                <span slot="communityBenefits" slot-scope="text, record">
                  <a-input-number
                    v-model="record.communityBenefits"
                    :min="0"
                    :max="99"
                    :formatter="value => value ? `${value}%` : ''"
                    :parser="value => value.replace('%', '')"
                    style="width:100%"
                  />
                </span>
                <span slot="action" slot-scope="text, record">
                  <a @click="onHandleEdit(record)">删除</a>
                </span>
              </a-table>
            </div>
          </div>
          <my-popup
            :showModal="false"
            ref="villageRef"
            title="选择小区"
            :multi="true"
            url="/property-company/community/companyCommunity/queryCommunityList"
            :columns="villageColumns"
            @callback="onChoseVillage"
          />


          <template v-if="model.rangeType === 'all'">
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="总平台分利" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="saasBenefits">
                  <!-- <a-input v-model="model.saasBenefits" suffix="%" placeholder="请输入总平台分利"></a-input> -->
                  <a-input-number
                    v-model="model.saasBenefits"
                    :min="0"
                    :max="99"
                    placeholder="总平台分利"
                    :formatter="value => value ? `${value}%` : ''"
                    :parser="value => value.replace('%', '')"
                    style="width:100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="合作伙伴分利" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="partnerBenefits">
                  <!-- <a-input v-model="model.partnerBenefits" suffix="%" placeholder="请输入合作伙伴分利"></a-input> -->
                  <a-input-number
                    v-model="model.partnerBenefits"
                    :min="0"
                    :max="99"
                    placeholder="合作伙伴分利"
                    :formatter="value => value ? `${value}%` : ''"
                    :parser="value => value.replace('%', '')"
                    style="width:100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="小区分利" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="communityBenefits">
                  <!-- <a-input v-model="model.communityBenefits" suffix="%" placeholder="请输入小区分利"></a-input> -->
                  <a-input-number
                    v-model="model.communityBenefits"
                    :min="0"
                    :max="99"
                    placeholder="小区分利"
                    :formatter="value => value ? `${value}%` : ''"
                    :parser="value => value.replace('%', '')"
                    style="width:100%"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <!-- <a-row> 
              <a-col :span="12">
                <a-form-model-item label="业主支付使用积分数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="legalName">
                  <a-input v-model="model.legalName" placeholder="抵扣物业费1元使用积分数"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="业主支付获取积分数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="registCapital">
                  <a-input-number v-model="model.registCapital" :min="1" placeholder="商品购买1元获取积分数" style="width: 100%" />
                </a-form-model-item>
              </a-col>
            </a-row> -->
          </template>
        </a-card>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import myPopup from '@/components/custom/myPopup'
import { addRuleDayDetailApi, getShareRuleDetailApi, editShareRuleDetailApi } from '@/api/api'

export default {
  name: 'PropertySettledForm',
  inject: ['closeCurrent'],
  components: {
    myPopup
  },
  data() {
    return {
      title: '',
      pageType: '',
      model: {
        ruleName: '',
        partnerId: '',
        partnerCode: '',
        partnerName: '',
        judgingCondition: '>',
        rangeType: 'all',
        shopNum: '',

        saasBenefits: '',
        partnerBenefits: '',
        communityBenefits: ''
      },
      validatorRules: {
        ruleName: [{ required: true, message: '请输入分利规则名称', trigger: 'blur' }],
        payUsePoints: [{ required: true, message: '请输入积分', trigger: 'blur' }],
        payGetPoints: [{ required: true, message: '请输入积分', trigger: 'blur' }]
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      url: {
        add: '/property-central/property/propertySettled/add',
        edit: '/property-central/property/propertySettled/edit',
        queryById: '/property-central/property/propertySettled/queryById',

        list: '/property-central/property/communityReconciliation/communityAccountPage'
      },
      partnersColumns: [
        {
          title: '合作伙伴名称',
          dataIndex: 'partnersName',
          key: 'partnersName',
          align: 'center',
        },
        {
          title: '联系人',
          dataIndex: 'contactName',
          key: 'contactName',
          align: 'center',
        },
        {
          title: '联系电话',
          dataIndex: 'contactPhone',
          key: 'contactPhone',
          align: 'center',
        },
        {
          title: '入驻时间',
          dataIndex: 'createTime',
          key: 'createTime',
          align: 'center',
        }
      ],
      villageColumns: [
        {
          title: '小区名称',
          dataIndex: 'communityName',
          key: 'communityName',
          align: 'center',
        },
        {
          title: '物业公司',
          dataIndex: 'platformName',
          key: 'platformName',
          align: 'center',
        },
        {
          title: '管理员',
          dataIndex: 'adminName',
          key: 'adminName',
          align: 'center',
        },
        {
          title: '电话',
          dataIndex: 'adminPhone',
          key: 'adminPhone',
          align: 'center',
        },
        {
          title: '添加时间',
          dataIndex: 'createTime',
          key: 'createTime',
          align: 'center',
        }
      ],
      villageDataSource: [],
      villageBenefitsColumns: [
        {
          title: '小区名称',
          dataIndex: 'communityName',
          key: 'communityName',
          align: 'center',
        },
        {
          title: '业主数量',
          dataIndex: 'ownerNum',
          key: 'ownerNum',
          align: 'center',
        },
        {
          title: '商铺数量',
          dataIndex: 'shopNum',
          key: 'shopNum',
          align: 'center',
        },
        {
          title: '总平台分利',
          dataIndex: 'saasBenefits',
          scopedSlots: { customRender: 'saasBenefits' },
          key: 'saasBenefits',
          align: 'center',
        },
        {
          title: '合作伙伴分利',
          dataIndex: 'partnerBenefits',
          scopedSlots: { customRender: 'partnerBenefits' },
          key: 'partnerBenefits',
          align: 'center',
        },
        {
          title: '小区分利',
          dataIndex: 'communityBenefits',
          scopedSlots: { customRender: 'communityBenefits' },
          key: 'communityBenefits',
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          fixed: 'right',
          width: 150,
        }
      ]
    }
  },
  methods: {
    async getPageDetail() {
      let { result } = await getShareRuleDetailApi({ id: this.$route.query.id })
      this.model = {...result}
      this.villageDataSource = [...result.shareRuleRefList]
    },
    onCancel() {
      this.closeCurrent()
    },
    onChosePartners(list) {
      if(list) {
        const row = list[0]
        this.model.partnerId = row.id
        this.model.partnerCode = row.platformCode
        this.model.partnerName = row.partnersName
      } else {
        this.model.partnerId = ''
        this.model.partnerCode = ''
        this.model.partnerName = ''
      }
    },
    onChoseVillage(list) {
      this.villageDataSource = list.map(item=> {
        return {
          ...item,
          saasBenefits: '',
          partnerBenefits: '',
          communityBenefits: ''
        }
      })
    },
    onHandleEdit(row) {
      let currentKey = this.villageDataSource.findIndex(item=>item.id === row.id)
      this.villageDataSource.splice(currentKey, 1)
    },
    onHandleAddVillage() {
      this.$refs.villageRef.$refs.jPopupOnlReport.show()
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let isOk = true
          for(let i = 0;i < this.villageDataSource.length;i++) {
            if(this.villageDataSource[i].saasBenefits == null) {
              isOk = false
              this.$message.warning(`请输入${this.villageDataSource[i].communityName}小区的总平台分利`);
              break
            }
            if(this.villageDataSource[i].partnerBenefits == null) {
              isOk = false
              this.$message.warning(`请输入${this.villageDataSource[i].communityName}小区的合作伙伴分利`);
              break
            }
            if(this.villageDataSource[i].communityBenefits == null) {
              isOk = false
              this.$message.warning(`请输入${this.villageDataSource[i].communityName}小区的小区分利`);
              break
            }
            if((this.villageDataSource[i].communityBenefits + this.villageDataSource[i].communityBenefits + this.villageDataSource[i].communityBenefits) > 100) {
              isOk = false
              this.$message.warning(`${this.villageDataSource[i].communityName}小区的分利比率不能大于100%`);
              break
            }
          }
          if(isOk) {
            this.confirmLoading = true
            let shareRuleRefList = this.villageDataSource.map(item=> {
              return {
                propertyCode: item.platformCode,
                propertyName: item.platformName,
                communityCode: item.communityCode,
                communityName: item.communityName,
                saasBenefits: item.saasBenefits,
                partnerBenefits: item.partnerBenefits,
                communityBenefits: item.communityBenefits,
                shopNum: item.shopNum,
                ownerNum: item.ownerNum
              }
            })
            if(this.$route.query.type == '1') {
              addRuleDayDetailApi({...this.model, shareRuleRefList}).then(res=> {
                this.$message.success(res.message);
                this.closeCurrent()
                this.confirmLoading = false
              }).catch(err=> {
                this.confirmLoading = false
              })
            } else {
              editShareRuleDetailApi({...this.model, shareRuleRefList}).then(res=> {
                this.$message.success(res.message);
                this.closeCurrent()
                this.confirmLoading = false
              }).catch(err=> {
                this.confirmLoading = false
              })
            }
          }
        }
      })
    }
  },
  mounted() {
    //备份model原始值
    //this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.pageType = this.$route.query.type
    if (this.$route.query.type == '1') {
      this.title = '新增'
    } else if (this.$route.query.type == '2') {
      this.title = '编辑'
      this.getPageDetail()
    } else if (this.$route.query.type == '3') {
      this.title = '详情'
      this.getPageDetail()
    }
  }
}
</script>
<style lang="less" scoped>
.title-top {
  background: #fff;
  padding: 0 25px;
  line-height: 50px;
  height: 50px;
  margin-bottom: 5px;
  h3 {
    font-weight: bold;
    display: inline-block;
  }
  .button {
    float: right;
    .ant-btn {
      margin-left: 15px;
    }
  }
}
</style>
<style>
.area-select {
  width: 100% !important;
}
</style>