<template>
  <Drawer title="条件设置" :value="conditionDrawer" placement="right" class="condition_copyer" width="550px"
          :closable="false" @on-close="setCondition(false)">
    <!--    {{dataFields}}-->
    <div class="drawer-content drawer-content-condition">
      <div v-if="defaultApprovalDrawer" class="default-style">其他情况</div>
      <div v-else>
        <!--      {{conditionConfig.conditionList}}-->
        <div v-for="(item, index) in conditionConfig.conditionList" :key="index">
          <div class="condition-conent-group">
            <div class="condition-group-title flex">
              <div class="dang-style">条件组</div>
              <div>
                <i class="remove el-icon-delete" @click="removeCondition('group', index)"></i>
              </div>
            </div>
            <!--                                {{item.conditionChildrenNodes}}-->
            <div class="condition-group-select" v-for="(it, ind) in item.conditionChildrenNodes" :key="ind">
              <div class="mg-bot-10">
                <div v-if="ind === 0" class="flex flex-style">
                  <span class="dang-style">当</span>
                  <!--                  {{it.unit}}-->
                </div>
                <div v-else class="flex">
                  <Select style="width: 110px;" v-model="it.conditionOperator" placeholder="请选择">
                    <Option label="且" :value="'&&'"></Option>
                    <Option label="或" :value="'||'"></Option>
                  </Select>
                </div>
              </div>
              <!--              {{it}}-->
              <!--条件表单部分-->
              <Form ref="formInline" name="dk-form" :rules="ruleInline" :model="it">
                <Row :gutter="5" class="mg-bot-10">
                  <Col :span="8">
                    <FormItem prop="leftUuid">
                      <Select v-model="it.leftUuid" placeholder="请选择" @on-change="changeLeftFields(it)">
                        <Option v-for="item in dataFields" :label="item.itemName" :value="item.itemUuid"
                                :key="item.itemUuid"></Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col :span="5">
                    <FormItem prop="centerFields">
                      <Select v-model="it.centerFields" placeholder="请选择">
                        <Option v-for="item in it.operatorList" :label="item.key" :value="item.value"
                                :key="item.key"></Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col :span="10">
                    <FormItem prop="rightFields">
                      <!--                    {{it.unit}}-->
                      <!--                  <DatePicker v-model="it.rightFields" v-if="it.leftFieldsType === 'date'" type="date"-->
                      <!--                              placeholder="选择日期" value-format="yyyy-MM-dd">-->
                      <!--                  </DatePicker>-->
                      <SelectPop ref="rightSelect" v-if="it.leftFields === 'orgId'" v-model="it.rightFields"
                                 :options="orgList" :multiple="true"
                                 label-key="orgName" value-key="orgId"/>
                      <SelectPop ref="rightSelect" v-else-if="it.leftFields === 'promotionPriceType'"
                                 v-model="it.rightFields" :options="promotionPriceTypeList" :multiple="true"
                                 label-key="typeName" value-key="typeId" :title="$t('promotionPriceType')"/>
                      <Select ref="rightSelect" v-else-if="it.leftFields === 'docCode'" v-model="it.rightFields"
                              :options="docCodeList" placeholder="请选择">
                        <Option v-for="item in docCodeList" :label="item.key" :value="item.value"
                                :key="item.key"></Option>
                      </Select>
                      <InputNumberPercentPop ref="percent" v-else-if="it.unit" style="line-height: 28px;height: 28px;"
                                             v-model="it.rightFields" placeholder="请输入" :digits="2" :unit="it.unit"
                                             :max="100.01" :min="0"></InputNumberPercentPop>
                      <InputNumberPop ref="base" v-else style="line-height: 28px;height: 28px" v-model="it.rightFields"
                                      placeholder="请输入" :digits="2" :negative="true"></InputNumberPop>
                    </FormItem>
                  </Col>
                  <i class="remove el-icon-delete" @click=" removeCondition( 'oneCondition', index, ind ) "></i>
                </Row>
              </Form>
            </div>
            <div class="conditionbtn">
              <Button @click="addConditionGroup('1', item)">
                <i class="el-button-suffix el-icon-plus"></i>添加条件
              </Button>
            </div>
          </div>
          <div v-if="conditionConfig.conditionList.length > 1 &&conditionConfig.conditionList.length-index>1"
               class="flex"
               style="height:54px;padding:0 24px">
            <Select style="width: 110px;margin-top:7px" v-model="item.conditionGroupOperator" placeholder="请选择">
              <Option label="且" :value="'&&'"></Option>
              <Option label="或" :value="'||'"></Option>
            </Select>
          </div>
        </div>

        <!--底部按钮-->
        <div class="conditionbtn">
          <Button @click="addConditionGroup('0')">
            <i class="el-button-suffix el-icon-plus"></i>添加条件组
          </Button>
        </div>
      </div>
    </div>
    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" @click="setCondition(false)">取 消</Button>
      <Button type="primary" @click="saveCondition">确 定</Button>
    </div>
  </Drawer>
</template>

<script>
import {formMixin} from '@/mixins/form'
import {mapState, mapMutations} from 'vuex'

export default {
  mixins: [formMixin],
  props: {
    dataFields: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  data() {
    let checkRightFields = (rule, value, callback) => {
      if (Array.isArray(value) && value.length == 0) {
        callback(new Error())
      } else {
        callback()
      }
    }
    return {
      resultArr: [],//接受验证返回结果数组
      ruleInline: {
        leftUuid: [
          {required: true, trigger: 'none', message: ' '},
        ],
        centerFields: [
          {required: true, trigger: 'none', message: ' '},
        ],
        rightFields: [
          {required: true, trigger: 'none', type: 'any', message: ' ', validator: checkRightFields},
        ],
      },
      docCodeList: [
        {key: '客户收款', value: 'RECEIPT_TYPE_COLLECTION'},
        {key: '客户取款', value: 'RECEIPT_TYPE_DRAW'},
      ],
      promotionPriceTypeList: [],
      orgList: [],
      baseOperatorList: [
        {key: '==', value: '=='},
        {key: '!=', value: '!='},
        {key: '>', value: '>'},
        {key: '>=', value: '>='},
        {key: '<', value: '<'},
        {key: '<=', value: '<='},
      ],
      multipleOperatorList: [
        {key: '属于', value: 'in'},
        {key: '不属于', value: 'notIn'}
      ],
      singleOperatorList: [
        {key: '==', value: '=='},
        {key: '!=', value: '!='},
      ],
      defaultApprovalDrawer: false, //默认条件弹框
      conditionVisible: false,
      conditionsConfig: {
        conditionNodes: [],
      },
      conditionConfig: {},
      PriorityLevel: '',
      conditions: [],
      conditionList: [],
      checkedList: [],
      conditionRoleVisible: false,
    }
  },
  computed: {
    ...mapState(['tableId', 'conditionsConfig1', 'conditionDrawer']),
  },
  watch: {
    conditionsConfig1(val) {
      this.conditionsConfig = val.value
      this.PriorityLevel = val.priorityLevel
      this.conditionConfig = val.priorityLevel
        ? this.conditionsConfig.conditionNodes[val.priorityLevel - 1]
        : {nodeObjectList: [], conditionList: []}
    },
    dataFields() {
      this.dataFields.forEach((it) => {
        if (it.itemTags && it.itemTags.operator) {
          this.$set(it, 'operatorList', this.getOperator(it.itemTags.operator))
        }
      })
    }
  },
  methods: {
    ...mapMutations(['setCondition', 'setConditionsConfig']),

    keydown(e) {
      // console.log('keydown',e)
    },
    /**
     * @desc   : 获取操作符
     * @author : 张潇木
     * @date   : 2022-8-23 9:47
     */
    getOperator(operator) {
      if (operator === "multiple") {
        return this.multipleOperatorList
      }
      if (operator === "single") {
        return this.singleOperatorList
      }
      return this.baseOperatorList
    },
    /**
     * @desc   : 单个条件的校验
     * @author : 张潇木
     * @date   : 2022-8-23 13:29
     */
    validForm(form) {
      let self = this;
      let result = new Promise(function (resolve, reject) {
        form.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            reject()
          }
        })
      })
      self.resultArr.push(result) //push 得到promise的结果
    },
    /**
     * @desc   : 保存条件
     * @author : 张潇木
     * @date   : 2022-8-23 9:47
     */
    saveCondition() {
      let self = this;
      //清空校验状态
      self.resultArr = []
      if (self.$refs['formInline'].size == 0) {
        self.setCondition(false);
        return
      }
      self.$refs['formInline'].forEach(it => {
        self.validForm(it)
      })
      Promise.all(self.resultArr).then(function () { //都通过了
        self.submit()
      }).catch(function () {
        return;
      });

    },
    /**
     * @desc   : 提交保存
     * @author : 张潇木
     * @date   : 2022-8-23 13:32
     */
    submit() {
      let index = 0
      this.conditionConfig.conditionList.forEach((it) => {
        it.conditionChildrenNodes.forEach((item) => {
          if (item.leftFields === 'orgId' || item.leftFields === 'promotionPriceType') {
            this.$set(item, 'rightFieldsName', this.$refs.rightSelect[index].getDisplayText())
            index++
          } else if (item.leftFields === 'docCode') {
            this.$set(item, 'rightFieldsName', this.docCodeList.find((code) => {
              return code.value === item.rightFields
            }).key)
          } else {
            this.$set(item, 'rightFieldsName', item.rightFields)
          }
        })
      })
      for (var i = 0; i < this.conditionsConfig.conditionNodes.length; i++) {
        this.conditionsConfig.conditionNodes[i].error = this.$appfunc.conditionStr(this.conditionsConfig, i) == "请设置条件" && i != this.conditionsConfig.conditionNodes.length - 1
      }
      this.setCondition(false)
      this.setConditionsConfig({
        value: this.conditionsConfig,
        flag: true,
        id: this.conditionsConfig1.id
      })
    },
    //删除条件组和条件
    removeCondition(conditonflag, index, ind) {
      if (conditonflag === 'group') {
        this.conditionConfig.conditionList.splice(index, 1)
        return
      }
      this.conditionConfig.conditionList[index].conditionChildrenNodes.splice(ind, 1)
      if (this.conditionConfig.conditionList[index].conditionChildrenNodes.length == 0) {
        this.conditionConfig.conditionList.splice(index, 1)
      }
    },
    //条件字段显示name
    changeLeftFields(it) {
      // console.log(' this.$refs', this.$refs)
      // if( this.$refs.input&&this.$refs.input.length>0){
      //   this.$refs.input[0].clearUnit()
      // }
      // if( this.$refs.percent&&this.$refs.percent.length>0){
      //   this.$refs.percent[0].clearUnit()
      // }
      // this.$refs.input[0].clearUnit()
      // console.log('this.dataFields', this.dataFields,it)
      this.dataFields.forEach((item) => {
        if (item.itemUuid === it.leftUuid) {
          // console.log('item',item)
          this.$set(it, 'leftFields', item.objectName)
          this.$set(it, 'leftFieldsName', item.itemName)
          this.$set(it, 'operatorList', item.operatorList)
          this.$set(it, 'unit', item.itemTags.unit)
          this.$set(it, 'centerFields', undefined)
          if (item.itemTags && item.itemTags.operator && item.itemTags.operator === 'base') {
            this.$set(it, 'rightFields', 0)
          } else {
            this.$set(it, 'rightFields', undefined)
          }

          // this.$set(it, 'leftFieldsType', item.type)
        }
      })
    },
    //添加条件/组
    addConditionGroup(flag, item) {
      //添加条件
      if (flag === '1') {
        item.conditionChildrenNodes.push({
          conditionOperator: '&&',
          leftFields: undefined,
          centerFields: undefined,
          rightFields: 0,
          operatorList: undefined,
        })
        // console.log('addConditionGroup', JSON.stringify(this.conditionConfig.conditionList))
        return
      }
      //添加条件组
      this.conditionConfig.conditionList.push({
        conditionChildrenNodes: [{
          conditionOperator: '&&',
          leftFields: undefined,
          centerFields: undefined,
          rightFields: 0,
          operatorList: undefined,
        }],
        conditionGroupOperator: '||',
      })
    },
    /**
     * @desc   : 查询业务部门下拉控件数据源
     * @author : 张潇木
     * @date   : 2022-6-13 13:28
     */
    getOrgList() {
      let params = {
        ftyId: this.$store.state.user.ftyId,
      }
      this.excute(this.$service.commonService, this.$service.commonService.getOrg, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.orgList = res.data
        }
      })
    }
  },
  created() {
  },
  mounted() {
    this.getOrgList();  // 获取部门
    // this.getPromotionPriceType();
  }
}
</script>

<style lang="less" scoped>
/deep/ .ivu-form-item-content {
  line-height: 28px !important;
  height: 28px !important;
}

.percent {
  height: 28px !important;
  line-height: 28px !important;
  margin-top: 0px !important;
  width: 100%;
}

/deep/ .ivu-input-number-small input {
  height: 28px !important;
  line-height: 28px !important;
  margin-top: 0px !important;
  width: 100%;
}

/deep/ .ivu-input {
  border-radius: 4px !important;
}

/deep/ .ivu-select-small.ivu-select-multiple .ivu-tag {
  margin: -5px 4px 0 0 !important;
}

/deep/ .close-class {
  display: flex !important;
  align-items: center !important;
  right: 20px !important;
}

/deep/ .ivu-form-item {
  margin-bottom: 0px !important;
}

/deep/ .ivu-select-single .ivu-select-selection .ivu-select-selected-value {
  height: 28px !important;
  line-height: 28px !important;
}

/deep/ .ivu-select-single .ivu-select-selection {
  line-height: 28px !important;
  height: 28px !important;
}

/deep/ .ivu-input {
  height: 28px !important;
  line-height: 28px !important;
}

.condition_copyer {
  .el-drawer__body {
    .priority_level {
      position: absolute;
      top: 11px;
      right: 30px;
      width: 100px;
      height: 28px;
      background: rgba(255, 255, 255, 1);
      border-radius: 4px;
      border: 1px solid rgba(217, 217, 217, 1);
    }
  }

  .condition_content {
    padding-top: 20px;

    p.tip {
      margin: 20px 0;
      width: 510px;
      text-indent: 17px;
      line-height: 45px;
      background: rgba(241, 249, 255, 1);
      border: 1px solid rgba(64, 163, 247, 1);
      color: #46a6fe;
      font-size: 14px;
    }

    ul {
      //max-height: 500px;
      overflow-y: scroll;
      margin-bottom: 20px;

      li {
        & > span {
          float: left;
          margin-right: 8px;
          width: 70px;
          line-height: 28px;
          text-align: right;
        }

        & > div {
          display: inline-block;
          width: 370px;

          & > p:not(:last-child) {
            margin-bottom: 10px;
          }
        }

        &:not(:last-child) > div > p {
          margin-bottom: 20px;
        }

        & > a {
          float: right;
          margin-right: 10px;
          margin-top: 7px;
        }

        select, input {
          width: 100%;
          height: 28px !important;
          background: rgba(255, 255, 255, 1);
          border-radius: 4px;
          border: 1px solid rgba(217, 217, 217, 1);
        }

        select + input {
          width: 260px;
        }

        select {
          margin-right: 10px;
          width: 100px;
        }

        p.selected_list {
          padding-left: 10px;
          border-radius: 4px;
          min-height: 28px;
          border: 1px solid rgba(217, 217, 217, 1);
          word-break: break-word;
        }

        p.check_box {
          line-height: 28px;
        }
      }
    }

    .el-button {
      margin-bottom: 20px;
    }
  }
}

.condition_list {
  .el-dialog__body {
    padding: 16px 26px;
  }

  p {
    color: #666666;
    margin-bottom: 10px;

    & > .check_box {
      margin-bottom: 0;
      line-height: 36px;
    }
  }
}

.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  right: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}

.condition-conent-group {
  border-bottom: solid 1px #ebebeb;
  padding-bottom: 20px;

  .condition-group-title {
    padding: 0 24px;
    background: #f7f8fa;
    height: 48px;
    border-top: solid 1px #ebebeb;
    border-bottom: solid 1px #ebebeb;
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .condition-group-select {
    padding: 0 24px;
  }

  .remove {
    color: #828282;

    &:hover {
      cursor: pointer;
      color: #4880ff;
    }
  }

  .mg-bot-10 {
    margin-bottom: 10px;
  }

}

.drawer-content-condition {
  overflow-y: auto;
  height: calc(~'100% - 53px');
  max-height: calc(~'100% - 53px');
  padding-bottom: 53px;

  .condition-conent-group {
    border-bottom: solid 1px #ebebeb;
    padding-bottom: 20px;

    .condition-group-title {
      padding: 0 24px;
      background: #f7f8fa;
      height: 48px;
      border-top: solid 1px #ebebeb;
      border-bottom: solid 1px #ebebeb;
      margin-bottom: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .condition-group-select {
      padding: 0 24px;
    }

    .remove {
      color: #828282;
      display: flex;
      align-items: center;
      height: 32px;

      &:hover {
        cursor: pointer;
        color: #4880ff;
      }
    }

    .mg-bot-10 {
      margin-bottom: 10px;
    }

    .conditionbtn {
      .el-button {
        border: 1px dashed #4880ff;
        width: 110px;
      }
    }
  }

  .conditionbtn {
    padding: 0 24px;
    margin-top: 26px;

    .el-button {
      border: solid 1px #4880ff;
      color: #4880ff;
      width: 123px;
    }
  }
}
</style>
