<template>
  <div class="main">
    <v-tour name="pushformTour" :steps="steps" :options="tourOptions" />
    <el-form
      id="pushform"
      ref="pushform"
      :model="pushform"
      :rules="pushrules"
      label-width="125px"
    >
      <div class="main_top">
        <p class="common-title">填写任务信息</p>
        <div>
          <el-button
            v-if="this.$route.query.type == '1'"
            @click="handleCancle"
          >取消</el-button>
          <el-button type="primary" @click="handleCommit">提交</el-button>
          <el-button type="warning" disabled>暂存草稿</el-button>
        </div>
      </div>
      <div id="fillInformationOne" class="fillInformation">
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="任务名称" prop="campaignName">
              <el-input
                v-model="pushform.campaignName"
                maxlength="30"
                placeholder="请输入任务名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="任务模式" prop="taskModel" class="required">
              <el-radio-group
                v-model="taskModel"
                @change="handleChangeTaskModel"
              >
                <el-radio label="0">普通任务</el-radio>
                <el-radio
                  label="1"
                >协作任务
                  <el-tooltip
                    placement="top"
                    trigger="hover"
                    content="总行分配给机构，由机构下成员共享任务数据，都可以共同完成走访，谁先完成归谁。"
                  >
                    <span
                      class="quesiton"
                    ><i
                      class="el-icon-question question_icon"
                    /></span> </el-tooltip></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="紧急程度" prop="campaignDegree">
              <el-select
                v-model="pushform.campaignDegree"
                placeholder="请选择紧急程度"
              >
                <el-option label="高" value="高" />
                <el-option label="中" value="中" />
                <el-option label="低" value="低" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="认领类型" prop="claimType">
              <el-select
                v-model="pushform.claimType"
                placeholder="请选择认领类型"
              >
                <el-option label="强制认领" value="0" />
                <!-- <el-option
                  label="可选认领"
                  value="1"
                  :disabled="taskModel === '1'"
                /> -->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="任务时间" prop="taskDate">
              <el-date-picker
                v-model="pushform.taskDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="picktaskDateOption"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="认领时间" prop="claimDate" style="flex: 1">
              <el-date-picker
                v-model="pushform.claimDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickclaimDateOption"
                value-format="yyyy-MM-dd"
                @change="handleClaimDate"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="任务类型" prop="taskType">
              <el-radio-group v-model="pushform.taskType" width="100%">
                <el-radio label="0">营销任务</el-radio>
                <el-radio label="1" disabled>事务任务</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem" v-if="taskModel === '1' && (deptId+'').substring(0,3) == '932'">
          <el-col :span="24">
            <el-form-item label="是否隐藏客户列表" prop="hideList">
              <el-radio-group v-model="pushform.hideList" width="100%">
                <el-radio label="true">是</el-radio>
                <el-radio label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="走访网格" prop="areaCode">
              <el-cascader
                v-model="pushform.areaCode"
                :options="areaOptions"
                :show-all-levels="false"
                :props="{
                  label: 'name',
                  value: 'code',
                  emitPath: false
                }"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="pushform.taskType == '0'" class="formItem">
          <el-col :span="24">
            <el-form-item label="活动方式" prop="campaignType">
              <el-select
                v-model="pushform.campaignType"
                placeholder="请选活动方式"
                allow-create
                clearable
                filterable
              >
                <el-option
                  v-for="item in campaignTypeList"
                  :key="item.value"
                  :label="item.label"
                  :disabled="item.disabled"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col v-if="pushform.taskType == '0'" :span="24">
            <el-form-item label="考核目标" prop="checkTarget">
              <el-select
                v-model="pushform.checkTarget"
                placeholder="请选考核目标"
                allow-create
                clearable
                filterable
                @change="selectGoal"
              >
                <el-option
                  v-for="item in goalList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row class="formItem">
          <el-col :span="12" :offset="3">
            <el-form-item label="任务指标" prop="taskIndex">
              <el-input v-model="pushform.taskIndex" placeholder="请输入任务指标,如贷款时点余额较上年末时点余额提示50%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="12" :offset="3">
            <el-form-item label="奖励说明" prop="reward">
              <el-input v-model="pushform.reward" placeholder="描述任务指标完成的奖励" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="任务内容备注" prop="remark">
              <el-input
                v-model="pushform.remark"
                placeholder="描述该任务内容等信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row class="formItem">
          <el-col :span="12" :offset="3">
            <el-form-item label="反馈要求" prop="feedBack">
              <el-checkbox-group v-model="pushform.feedBack">
                <el-checkbox label="无"></el-checkbox>
                <el-checkbox label="签到签退"></el-checkbox>
                <el-checkbox label="拍照"></el-checkbox>
                <el-checkbox label="反馈记录"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="12" :offset="3">
            <el-form-item label="上传反馈模版" prop="demand">
              <el-upload class="custom-el-upload" ref="upload" :on-change="handleFileChange" :file-list="fileList"
                :auto-upload="false" :on-remove="handleRemove" action="#" accept=".csv" disabled>
                <el-button type="primary" disabled>上传文件</el-button>
                <div slot="tip">请上传csv文件，大小在60M以内</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row> -->
      </div>
      <div class="fillInformation">
        <p class="common-title">选择客户</p>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="客户类型" prop="custType">
              <el-select
                v-model="pushform.custType"
                placeholder="请选择客户类型"
                @change="handleGroupType"
              >
                <el-option
                  v-for="(item, index) in custTypeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="走访类型" prop="visitType">
              <el-radio-group v-model="pushform.visitType" width="150%">
                <el-radio label="企业走访">企业走访</el-radio>
                <el-radio label="商户走访">商户走访</el-radio>
                <el-radio label="个人走访">个人走访</el-radio>
                <el-radio label="收单商户走访">收单商户走访</el-radio>
                <el-radio label="域外商会走访">域外商会走访</el-radio>
                <el-radio label="催收走访">催收走访</el-radio>
                <el-radio label="竞争性走访">竞争性走访</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="选择客户" prop="groupId" class="item-group">
              <el-select
                v-model="pushform.groupId"
                placeholder="请选择分群"
                :multiple="true"
              >
                <!-- <el-option label="分群" value="0"></el-option> -->
                <el-option
                  v-for="(item, index) in groupIdList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <div class="createBtn">
                <el-button type="primary" @click="goToCreate">去创建</el-button>
                <p>没有合适的客群?</p>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="formItem">
          <el-col :span="24">
            <el-form-item label="反馈模板" prop="">
              <el-select
                v-model="pushform.relatedModelId"
                clearable
                placeholder="请选择反馈模板"
              >
                <el-option
                  v-for="(item, index) in modelOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div id="fillInformationThird" class="fillInformation">
        <p class="common-title">分配规则</p>
        <el-row
          v-if="
            this.shyh == '总行' ||
              this.isPublic ||
              this.isPrivate ||
              this.isHeadOps
          "
          class="formItem"
        >
          <el-col :span="24">
            <el-form-item label="执行人" prop="executer">
              <el-radio-group v-model="pushform.executer">
                <el-radio label="0">支行</el-radio>
                <el-radio
                  label="1"
                  :disabled="taskModel === '1'"
                >个人</el-radio>
                <el-radio
                  label="2"
                  :disabled="taskModel === '1'"
                >混合分配</el-radio>
                <el-radio label="3">网点</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="taskModel !== '1'" class="formItem">
          <el-col :span="24">
            <div v-for="(rule, index) in configRules" :key="index">
              <div class="ruleBox">
                <custom-rule
                  :key="rule.key"
                  :rule-title="rule.ruleTitle"
                  :default-list-data="rule.defaultListData"
                  :dept-options="deptOptions"
                  :rule-id="ruleId"
                  :rule-name="rule.ruleName"
                  :cust-type="pushform.custType"
                  :rule-index="index"
                  :special-type="true"
                  :is-other-style="true"
                  @getRuleArr="getRuleArr"
                />
                <!-- <el-button type="primary" icon="el-icon-delete"
                  @click="delNewRules(index)"
                  v-if="configRules.length>1"
                  class="del-btn"
                >删除</el-button> -->
              </div>
            </div>
            <!-- <el-button class="add-btn" type="primary" icon="el-icon-plus"  @click="addNewRules" v-if="pushform.custType">添加新的分配规则</el-button> -->
          </el-col>
        </el-row>
        <el-row v-else class="formItem">
          <el-col :span="24">
            <el-form-item label="执行机构" prop="cooperateDeptId">
              <treeselect
                ref="orgTree"
                v-model="pushform.cooperateDeptId"
                :options="belongDeptOptions"
                placeholder="请选择"
                no-options-text="暂无数据"
                no-results-text="暂无数据"
                :flat="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <!-- <div class="fillInformation">
        <p class="common-title">分配渠道</p>
        <el-row class="formItem">
          <el-col :span="12" :offset="3">
            <el-form-item label="分配渠道" prop="qudao">
              <el-select v-model="pushform.qudao" placeholder="请选择分配渠道">
                <el-option v-for="(item, index) in qudaoList" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div> -->
    </el-form>
    <el-dialog
      title="考核目标"
      :visible.sync="goalVisible"
      width="300px"
      append-to-body
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-input v-model="dialogGoal" type="textarea" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleGoalCommit">确定</el-button>
        <el-button @click="handleGoalCancle">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getDeptUserTree } from '@/api/grid/address/tree.js'
import { getUserProfile } from '@/api/grid/anchor.js'
import { Message } from 'element-ui'
import {
  getGroupList,
  addCampaign,
  addCoopCampaign,
  getCmpmByCustType,
  getCampaignModelList,
  getAreaIn,
  getAreaOut
} from '@/api/task/taskList.js'
import CustomRule from '../../grid/visit/checklist/custom-rule.vue'
import { isHead } from '@/api/system/findCustByGroupId.js'
import { getDeptTree } from '@/api/grid/address/tree.js'
import { mapGetters } from 'vuex'
import { uid } from '@/utils'
import { cloneDeep, isEmpty } from 'lodash'
import { resolve } from 'path'
import { rejects } from 'assert'
export default {
  components: { CustomRule },
  data() {
    return {
      steps: [
        {
          target: '#fillInformationOne',
          content:
            '<div style="font-size:20px;line-height:25px">填写任务信息，星号为必填</div><br><span></span>',
          overlay: true,
          params: {
            placement: 'right',
            highlight: true,
            mask: true,
            enableScrolling: false
          }
        },
        {
          target: '#fillInformationThird',
          content:
            '<div style="font-size:20px;line-height:25px">配置分配规则</div><br><span>点击提交即可在任务列表查看</span>',
          overlay: true,
          params: {
            placement: 'top',
            highlight: true,
            mask: true
          }
        },
        {
          target: '#fillInformationThird',
          content: '',
          overlay: true,
          before: () => {
            return this.$router
              .push({ path: '/taskManage/taskList' })
              .then(() => {
                return new Promise((resolve) => {
                  const checkElement = () => {
                    if (document.querySelector('#fillInformationOne')) {
                      resolve()
                    } else {
                      setTimeout(checkElement, 100)
                    }
                  }
                  checkElement()
                })
              })
          }
        }
      ],
      tourOptions: {
        highlight: true,
        labels: {
          buttonSkip: '跳过',
          buttonPrevious: '上一步',
          buttonNext: '下一步',
          buttonStop: '完成'
        },
        enabledButtons: {
          buttonSkip: true,
          buttonPrevious: true,
          buttonNext: true,
          buttonStop: true
        },
        useKeyboardNavigation: true,
        startTime: 0,
        stopOnTargetNotFound: true,
        debug: false
      },
      isAddRuleDisable: true,
      pushform: {
        campaignName: '',
        areaCode: '',
        campaignDegree: '',
        claimType: '0',
        taskDate: [],
        claimDate: [],
        taskType: '',
        visitType: '',
        campaignType: '',
        checkTarget: '',
        taskIndex: '',
        reward: '',
        remark: '',
        feedBack: [],
        custType: '',
        groupId: '',
        executer: '',
        relatedModelId: '',
        cooperateDeptId: null,
        hideList: 'false'
      },
      taskModel: '0',
      belongDeptOptions: [],
      goalVisible: false,
      dialogGoal: '',
      groupIdList: [],
      defaultGroupIdList: [],
      custTypeList: [],
      fileList: [],
      dialogYx: '',
      goalList: [
        { label: '自定义', value: '7' },
        { label: '存款营销', value: '存款营销' },
        { label: '贷款营销', value: '贷款营销' },
        { label: '产品营销', value: '产品营销' },
        { label: '贷前调查', value: '贷前调查' },
        { label: '贷后回访', value: '贷后回访' },
        { label: '逾期催收', value: '逾期催收' }
      ],
      campaignTypeList: [
        { label: '电话', value: '电话', disabled: true },
        { label: '短信', value: '短信', disabled: true },
        { label: '走访', value: '走访' }
      ],
      allOcationuleList: [{ ruleName: '' }],

      pushrules: {
        campaignName: [{ required: true, message: '任务名称不能为空' }],
        campaignDegree: [{ required: true, message: '请选择紧急程度' }],
        claimType: [{ required: true, message: '请选择认领类型' }],
        taskDate: [{ required: true, message: '请选择任务时间' }],
        claimDate: [{ required: true, message: '请选择认领时间' }],
        taskType: [{ required: true, message: '请选择任务类型' }],
        campaignType: [{ required: true, message: '请选择活动方式' }],
        checkTarget: [{ required: true, message: '请选择考核目标' }],
        visitType: [{ required: true, message: '请选择走访类型' }],
        custType: [{ required: true, message: '请选择客户类型' }],
        groupId: [
          {
            required: true,
            message: '请选择客户',
            trigger: 'change',
            validator: (rule, value, callback) => {
              console.log(value)
              if (
                (isEmpty(value) || !value.length) &&
                this.groupIdList.length
              ) {
                callback(new Error('客户不能为空'))
              } else {
                callback()
              }
            }
          }
        ],
        executer: [{ required: true, message: '请选择执行人' }],
        qudao: [{ required: true, message: '请选择分配渠道' }],
        cooperateDeptId: [{ required: true, message: '请选择执行机构' }]
      },
      accountManager: [],
      userList: [],
      picktaskDateOption: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      pickclaimDateOption: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      deptId: '',
      ruleMap: { personal: [] },
      deptOptions: [],
      ruleArr: [],
      ruleId: '3',
      shyh: '',
      // configNewRules:[{
      //     ruleTitle: '分配规则',
      //     ruleName: 'personal',
      //     key: uid()
      //   }],
      qudaoList: [
        { label: '存款营销1', value: '1' },
        { label: '存款营销2', value: '2' },
        { label: '存款营销3', value: '3' }
      ],
      configRules: [
        {
          ruleTitle: '分配规则',
          ruleName: 'personal',
          key: uid()
        }
      ],
      managerOptions: [],
      modelOptions: [], // 反馈模板列表
      areaOptions: []
    }
  },
  watch: {
    allOcationuleList: {
      handler(arr) {
        arr.forEach((item) => {
          this.ownershipList.forEach((el) => {
            if (item.ruleName == el.value) {
              el.disabled = true
            }
          })
        })
      }
      // deep:true
    }
  },
  computed: {
    ...mapGetters(['roles']),
    // 对公
    isPublic() {
      return this.roles.includes('headPublic')
    },
    // 对私
    isPrivate() {
      return this.roles.includes('headPrivate')
    },
    // 运管部
    isHeadOps() {
      return this.roles.includes('headOps')
    },
    isSegTour() {
      return sessionStorage.getItem('isSegTour')
    }
    // configRules() {

    //   const newArr = []
    //   if (this.pushform.custType == '0') {
    //     newArr.push({
    //       ruleTitle: '分配规则',
    //       ruleName: 'personal',
    //       key: uid()
    //     })
    //     this.ruleMap.personal = [

    //     ]
    //   }

    //   if (this.pushform.custType == '1') {
    //     newArr.push({
    //       ruleTitle: '分配规则',
    //       ruleName: 'merchant',
    //       key: uid()
    //     })
    //     this.ruleMap.merchant = [

    //     ]
    //   }

    //   if (this.pushform.custType == '2') {
    //     newArr.push({
    //       ruleTitle: '分配规则',
    //       ruleName: 'company',
    //       key: uid()
    //     })
    //     this.ruleMap.company = [

    //     ]
    //   }
    //   console.log(newArr)
    //   // this.configNewRules = newArr
    //   return newArr
    // },
  },
  created() {
    this.isUserType()
    this.initGroupList()
    this.getDeptTreeSelect()
    if (this.isPublic) {
      this.custTypeList = [{ label: '企业', value: '2' }]
    } else if (this.isPrivate) {
      this.custTypeList = [
        { label: '个人', value: '0' },
        { label: '商户', value: '1' }
      ]
    } else {
      this.custTypeList = [
        { label: '个人', value: '0' },
        { label: '商户', value: '1' },
        { label: '企业', value: '2' }
      ]
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.getUser()
    })
    this.initAreaOptions()
    const { custType, groupId } = this.$route.query
    if (custType) {
      const newGroupId = JSON.parse(groupId)
      this.pushform.custType = custType
      this.handleGroupType(custType, newGroupId)
    }
    if (this.isSegTour == '1') {
      setTimeout(() => {
        this.startTour()
      }, 1000)
    }
  },
  methods: {
    startTour() {
      this.$tours['pushformTour'].start()
    },
    async initAreaOptions() {
      const res1 = await getAreaIn()
      const res2 = await getAreaOut()
      this.areaOptions = [
        { name: '域内', code: 'in', children: this.markTree(res1.data) || [] },
        { name: '域外', code: 'out', children: this.markTree(res2.data) || [] }
      ]
    },
    markTree(treeData) {
      const processNode = (node) => {
        const hasChildren =
          Array.isArray(node.children) && node.children.length > 0

        if (!hasChildren) {
          node.leaf = true
          if (node.children && node.children.length === 0) {
            delete node.children
          }
        } else {
          node.children.forEach((child) => processNode(child))
        }
      }

      if (Array.isArray(treeData)) {
        treeData.forEach((node) => processNode(node))
      }

      return treeData
    },
    handleClaimDate(val) {
      const rlStartDate = val ? Date.parse(new Date(val[0])) : ''
      const rlEndDate = val ? Date.parse(new Date(val[1])) : ''
      const taskStartDate = this.pushform.taskDate
        ? Date.parse(new Date(this.pushform.taskDate[0]))
        : ''
      const taskEndDate = this.pushform.taskDate
        ? Date.parse(new Date(this.pushform.taskDate[1]))
        : ''

      if (rlStartDate < taskStartDate) {
        Message.warning('认领开始时间需大于等于任务开始时间')
        this.pushform.claimDate = []
      }
      if (rlEndDate > taskEndDate) {
        Message.warning('认领结束时间需小于等于任务结束时间')
        this.pushform.claimDate = []
      }
      console.log(this.pushform.taskDate, 'pushform.taskDate')
    },
    handleChangeTaskModel(val) {
      if (val === '1') {
        this.pushform.claimType = '0'
        this.pushform.executer = '0'
      }
    },
    getModelList() {
      if (!this.pushform.custType) {
        this.modelOptions = []
        return
      }
      getCampaignModelList({ custType: this.pushform.custType }).then((res) => {
        if (res.code === 200) {
          this.modelOptions = Object.entries(res.data || {}).map(
            ([key, label]) => ({
              value: key,
              label: label
            })
          )
        }
      })
    },
    converDate() {
      return Date.parse(new Date())
    },
    getDeptTreeSelect() {
      getDeptTree().then((response) => {
        this.belongDeptOptions = response.data?.[0]?.children || []
        this.deptOptions = response.data
      })
    },
    isUserType() {
      isHead().then((res) => {
        if (Object.keys(res)[0] == 'headAdmin') {
          this.shyh = '总行'
        } else if (Object.keys(res)[0] == 'branchAdmin') {
          this.shyh = '支行'
        } else if (
          Object.keys(res)[0] == 'manager' ||
          Object.keys(res)[0] == 'outlet'
        ) {
          this.shyh = '客户经理'
        }
      })
    },
    getRuleArr(obj, index, managerOptions) {
      // console.log(index,obj,this.deptOptions,managerOptions);
      this.ruleMap[obj.ruleName] = obj.arr
      this.managerOptions = managerOptions
    },
    initGroupList() {
      const params = {
        groupType: '1'
      }
      if (this.isPublic) {
        params.type = '0'
      } else if (this.isPrivate) {
        params.type = '1'
      }
      getGroupList(params).then((res) => {
        // console.log(res)
        this.defaultGroupIdList = res.map((item) => {
          return {
            label: item.groupName,
            value: item.groupId,
            custType: item.custType
          }
        })
        this.groupIdList = cloneDeep(this.defaultGroupIdList)
      })
    },
    // handleGroup(val) {
    //   let arr = this.groupIdList.filter(item => item.value == val)
    //   this.pushform.custType = arr[0].custType
    // },
    // 切换客户类型
    handleGroupType(custType, groupId) {
      this.groupIdList = this.defaultGroupIdList.filter(
        (item) => item.custType == custType
      )
      console.log(this.groupIdList, groupId)
      if (groupId) {
        this.pushform.groupId = groupId
      } else {
        this.pushform.groupId = []
      }
      this.pushform.relatedModelId = ''
      this.configRules = []
      const ruleName =
        this.pushform.custType == '0'
          ? 'personal'
          : this.pushform.custType == '1'
            ? 'merchant'
            : this.pushform.custType == '2'
              ? 'company'
              : ''
      this.configRules.push({
        ruleTitle: '分配规则',
        ruleName,
        key: uid()
      })
      this.ruleMap[ruleName] = []
      this.getModelList()
    },
    async getUser() {
      await getUserProfile().then((res) => {
        this.deptId = res.data.dept.deptId
      })
    },
    selectUser() {
      const params = {
        deptid: this.deptId
      }
      getDeptUserTree(params).then((res) => {
        if (res.length > 0) {
          this.userList = res.map((item) => {
            return {
              value: item.userName,
              label: item.nickName
            }
          })
        }
      })
    },
    handleAddRules() {
      this.allOcationuleList.push({
        ruleName: ''
      })
    },
    handleDeleteRules(index, val) {
      this.allOcationuleList.splice(index, 1)
      this.ownershipList.forEach((item) => {
        if (item.value == val.ruleName) {
          item.disabled = false
        }
      })
    },
    selectGoal(val) {
      if (val == '7') {
        this.goalVisible = true
        this.dialogGoal = ''
      }
    },
    handleFileChange(file, fileList) {
      // 判断客户类型

      this.file = file
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
      }
      if (file.status === 'ready') {
        // alert(file.status)
        this.progressFlag = true
        this.loadProgress = 0
        const interval = setInterval(() => {
          if (this.loadProgress >= 100) {
            // alert(this.subCustType)

            clearInterval(interval)
            return
          }
          this.loadProgress += 1
        }, 20)
      }
      if (file.status == 'success') {
        this.progressFlag = false
        this.loadProgress = 100
      }
    },
    handleRemove() {},
    handleGoalCommit() {
      console.log(this.dialogGoal, 'this.dialogGoal')
      this.goalList.push({ label: this.dialogGoal, value: this.dialogGoal })
      this.pushform.checkTarget = this.dialogGoal
      console.log(this.pushform.checkTarget, 'this.this.pushform.checkTarget')
      this.goalVisible = false
    },
    handleGoalCancle() {
      this.pushform.checkTarget = ''
      this.goalVisible = false
    },
    handleYxCommit() {},
    handleYxCancle() {},
    formDataPamars(json) {
      const params = []
      for (const key in json) {
        const value = json[key]
        if (value && typeof value === 'object' && !Array.isArray(value)) {
          params.push(
            ...Object.keys(value).map(
              (k) => `${key}[${k}]=${encodeURIComponent(value[k])}`
            )
          )
        } else if (Array.isArray(value)) {
          value.forEach((item) => {
            params.push(`${key}[]=${encodeURIComponent(item)}`)
          })
        } else {
          params.push(`${key}=${encodeURIComponent(value)}`)
        }
      }
      return params.join('&')
    },
    handleCancle() {
      this.$router.go(-1)
    },

    getUserDeptNames(arr) {
      return arr.flatMap((item) => [
        item,
        ...this.getUserDeptNames(item.children || [])
      ])
    },
    handleCommit() {
      this.$refs.pushform.validate((valid) => {
        if (valid) {
          const params = {
            campaignName: this.pushform.campaignName,
            campaignDegree: this.pushform.campaignDegree,
            claimType: this.pushform.claimType,
            startTime: this.pushform.taskDate ? this.pushform.taskDate[0] + ' 00:00:00' : '',
            endTime: this.pushform.taskDate ? this.pushform.taskDate[1] + ' 23:59:59' : '',
            claimStartTime: this.pushform.claimDate
              ? this.pushform.claimDate[0] + ' 00:00:00'
              : '',
            claimEndTime: this.pushform.claimDate
              ? this.pushform.claimDate[1] + ' 23:59:59'
              : '',
            taskType: this.pushform.taskType,
            visitType: this.pushform.visitType,
            campaignType: this.pushform.campaignType,
            checkTarget: this.pushform.checkTarget,
            taskIndex: this.pushform.taskIndex,
            reward: this.pushform.reward,
            remark: this.pushform.remark,
            feedBack:
              this.pushform.feedBack.length > 0
                ? this.pushform.feedBack.join(',')
                : '',
            custType: this.pushform.custType,
            areaCode: this.pushform.areaCode,
            groupIds: this.pushform.groupId,
            executer: this.pushform.executer,
            relatedModelId: this.pushform.relatedModelId,
            cooperateDeptId: this.pushform.cooperateDeptId,
            hideList: this.pushform.hideList,
            createRole:
              this.shyh == '总行'
                ? '0'
                : this.shyh == '支行'
                  ? '5'
                  : this.isPublic
                    ? '2'
                    : this.isPrivate
                      ? '1'
                      : this.isHeadOps
                        ? '3'
                        : ''
          }
          if (this.taskModel === '0') {
            // 优化分配规则代码
            let newArr = []
            if (this.pushform.custType == '0') {
              newArr = this.ruleMap.personal
            } else if (this.pushform.custType == '1') {
              newArr = this.ruleMap.merchant
            } else if (this.pushform.custType == '2') {
              newArr = this.ruleMap.company
            }

            console.log(newArr)
            const distributeCont = newArr.map((item) => {
              return item.label
            })
            let distributeCont2 = []
            let distributeCont3 = []
            // console.log(this.deptOptions,newArr[newArr.length-1])
            const newDeptOptions = this.getUserDeptNames(this.deptOptions)
            // console.log(newDeptOptions)
            if (newArr[newArr.length - 1].ruleKey == '3') {
              // 随机分配
              distributeCont2 = newArr[newArr.length - 1].userDeptList.map(
                (i) => {
                  return newDeptOptions.map((item) => {
                    if (item.id == i) {
                      return item.label
                    }
                    return 'false'
                  })
                }
              )
              distributeCont3 = newArr[newArr.length - 1].userName.map((i) => {
                return this.managerOptions.map((item) => {
                  if (item.userId == i) {
                    return `${item.deptName}-${item.userName}-${item.nickName}`
                  }
                  return 'false'
                })
              })
              console.log(distributeCont2, 222)
              distributeCont2 = []
                .concat(...distributeCont2)
                .filter((item) => item != 'false')
              distributeCont3 = []
                .concat(...distributeCont3)
                .filter((item) => item != 'false')
            }
            params.distributeCont = distributeCont.join(',')
            params.distributeCont2 = distributeCont2.join(',')
            params.distributeCont3 = distributeCont3.join(',')
            // console.log(distributeCont2,distributeCont3)
            const arr = newArr.map((item) => {
              return item.ruleKey
            })
            console.log(arr, 'arr')
            const arr1 = arr.map((item) => {
              if (item.includes('+') || item.includes('--')) {
                return item.substring(0, 2)
              } else {
                return item
              }
            })
            // 特色网格组装
            const arrTswg = arr.filter((item) => item.includes('+'))
            const layerIdList = arrTswg.map((item) => {
              const itemList = item.split('+')
              return itemList.pop()
            })
            // 虚拟网格组装
            const arrXnwg = arr.filter((item) => item.includes('--'))
            const virtualGridIdsList = arrXnwg.map((item) => {
              const itemList = item.split('--')
              return itemList.pop()
            })
            params.distributeType = arr1.join(',')
            params.layerIds = layerIdList
            params.virtualGridIds = virtualGridIdsList
            const perArr = newArr.filter((item) => 'userName' in item)
            if (perArr && perArr.length > 0) {
              const perList = perArr[0].userName
              params.userIds = perList
            }

            // if (this.pushform.custType == '0') {
            //   // distributeType组装
            //   let arr = this.ruleMap.personal.map(item => { return item.ruleKey })
            //   let arr1 = arr.map(item => {
            //     if (item.includes('+') || item.includes('--')) {
            //       return item.substring(0, 2)
            //     } else {
            //       return item
            //     }
            //   })
            //   //特色网格组装
            //   let arrTswg = arr.filter(item => item.includes('+'))
            //   let layerIdList = arrTswg.map(item => {
            //     let itemList = item.split('+')
            //     return itemList.pop()
            //   })
            //   //虚拟网格组装
            //   let arrXnwg = arr.filter(item => item.includes('--'))
            //   let virtualGridIdsList = arrXnwg.map(item => {
            //     let itemList = item.split('--')
            //     return itemList.pop()
            //   })
            //   params.distributeType = arr1.join(',')
            //   params.layerIds = layerIdList.join(',')
            //   params.virtualGridIds = virtualGridIdsList.join(',')

            //   let perArr = this.ruleMap.personal.filter(item => 'userName' in item)
            //   if (perArr && perArr.length > 0) {
            //     let perList = perArr[0].userName
            //     params.userIds = perList.join(',')
            //   }
            // } else if (this.pushform.custType == '1') {
            //   let arr = this.ruleMap.merchant.map(item => { return item.ruleKey })
            //   let arr1 = arr.map(item => {
            //     if (item.includes('+') || item.includes('--')) {
            //       return item.substring(0, 2)
            //     } else {
            //       return item
            //     }
            //   })
            //   //特色网格组装
            //   let arrTswg = arr.filter(item => item.includes('+'))
            //   let layerIdList = arrTswg.map(item => {
            //     let itemList = item.split('+')
            //     return itemList.pop()
            //   })
            //   //虚拟网格组装
            //   let arrXnwg = arr.filter(item => item.includes('--'))
            //   let virtualGridIdsList = arrXnwg.map(item => {
            //     let itemList = item.split('--')
            //     return itemList.pop()
            //   })
            //   params.distributeType = arr1.join(',')
            //   params.layerIds = layerIdList.join(',')
            //   params.virtualGridIds = virtualGridIdsList.join(',')
            //   let perArr = this.ruleMap.merchant.filter(item => 'userName' in item)
            //   if (perArr && perArr.length > 0) {
            //     let perList = perArr[0].userName
            //     params.userIds = perList.join(',')
            //   }
            // } else if(this.pushform.custType == '2') {
            //   let arr = this.ruleMap.company.map(item => { return item.ruleKey })
            //   let arr1 = arr.map(item => {
            //     if (item.includes('+') || item.includes('--')) {
            //       return item.substring(0, 2)
            //     } else {
            //       return item
            //     }
            //   })
            //   //特色网格组装
            //   let arrTswg = arr.filter(item => item.includes('+'))
            //   let layerIdList = arrTswg.map(item => {
            //     let itemList = item.split('+')
            //     return itemList.pop()
            //   })
            //   //虚拟网格组装
            //   let arrXnwg = arr.filter(item => item.includes('--'))
            //   let virtualGridIdsList = arrXnwg.map(item => {
            //     let itemList = item.split('--')
            //     return itemList.pop()
            //   })
            //   params.distributeType = arr1.join(',')
            //   params.layerIds = layerIdList.join(',')
            //   params.virtualGridIds = virtualGridIdsList.join(',')
            //   let perArr = this.ruleMap.company.filter(item => 'userName' in item)
            //   if (perArr && perArr.length > 0) {
            //     let perList = perArr[0].userName
            //     params.userIds = perList.join(',')
            //   }
            // }
          }

          console.log(params, 'params')
          const API = this.taskModel === '0' ? addCampaign : addCoopCampaign
          // return;
          API(params).then((res) => {
            if (res.code == 200) {
              Message.success('添加成功')
              this.$router.push({ path: '/taskManage/taskList' })
            }
          })
        } else {
          return false
        }
      })
      console.log(this.pushform.checkTarget)
    },

    // 添加新的规则
    // addNewRules(){
    //   this.configNewRules.push({
    //     ruleTitle: '分配规则',
    //     ruleName: this.pushform.custType == '0'?'personal':
    //               this.pushform.custType == '1'?"merchant":
    //               this.pushform.custType == '2'?"company":'',
    //     key: uid()
    //   })
    // },

    // 删除规则
    // delNewRules(index){
    //   this.configNewRules.splice(index,1);
    // },

    // 去创建客群
    goToCreate() {
      this.$router.push({
        path: '/grid/create/segmentation'
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.main {
  padding: 30px 30px 100px 30px;
  background-color: #fff;
}

.main_top {
  display: flex;
  justify-content: space-between;
}

.common-title {
  position: relative;
  color: #222222;
  line-height: 35px;
  font-weight: 600;
  font-size: 16px;
  padding-left: 10px;
  margin: 0;

  &::before {
    position: absolute;
    top: 50%;
    transform: translatey(-50%);
    left: 0;
    content: "";
    width: 3px;
    background-color: #4886f8;
    height: 16px;
    border-radius: 2px;
  }
}

.fillInformation {
  margin-top: 20px;
  width: 50%;
  margin-left: 10%;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-date-editor {
  width: 100%;
}

::v-deep .el-form-item.required {
  .el-form-item__label {
    &::before {
      content: "*";
      color: #ff4949;
      margin-right: 4px;
    }
  }
}

.configRulesItem {
  display: flex;
  margin-bottom: 15px;
}

.yxjLabel {
  width: 20%;
}

.addIcon {
  font-size: 25px;
  line-height: 40px;
  margin-left: 10px;
}

.ruleIcon {
  width: 20%;
}

.kejlbox {
  display: flex;
  margin-top: 15px;
}

.kejlLabel {
  width: 20%;
  margin-right: 15px;
}

.item-group {
  position: relative;

  .createBtn {
    position: absolute;
    right: -130px;
    top: 0;

    p {
      color: #666;
      font-size: 12px;
    }
  }
}

.ruleBox {
  // border: 1px solid #ddd;
  position: relative;
  padding: 12px;

  .del-btn {
    position: absolute;
    right: 5px;
    top: 5px;
  }

  margin-bottom: 10px;
}

.formItem {
  .add-btn {
    margin-top: 5px;
  }
}

::v-deep .v-step::after {
  content: "";
  position: absolute;
  width: 100px;
  height: 100px;
  background-image: url("../../../assets/images/arrow.gif");
  background-repeat: no-repeat;
  background-size: contain;
  top: 0;
  left: 50%;
  z-index: 9999999;
}

::v-deep .v-step[data-popper-placement^="top"]::after {
  top: 75px;
  left: -40%;
}

::v-deep .v-step[data-popper-placement^="bottom"]::after {
  top: -60%;
  left: 0;
  transform: rotate(90deg);
}

::v-deep .v-step[data-popper-placement^="left"]::after {
  top: -50%;
  left: 155%;
}

::v-deep .v-step[data-popper-placement^="right"]::after {
  top: -190%;
  left: -155%;
}
</style>
<style>
@import "../../grid/tour.css";
</style>
