<!-- 绩效计件模板 -->
<template>
  <div>
    <Row align="middle" type="flex">
      <Input
        :maxlength="20"
        @on-change="restPage"
        clearable
        placeholder="模板名称"
        style="width: 200px"
        v-model="name"
      />
      <Button :loading="loading" @click="doInitSearch" class="mg-set" type="primary">查询</Button>

      <div class="table_data-control">
        <Button
          :disabled="loading"
          @click="infoAdd"
          ghost
          icon="md-add"
          type="primary"
          v-permission:add
        >新增</Button>
        <Modal
          :mask-closable="false"
          :styles="{width: '750px'}"
          :title="modalTitle"
          v-model="modalTmpl"
        >
          <Form :label-width="72" :model="formTmpl" :rules="ruleValidate" ref="formTmpl">
            <Row :gutter="8">
              <Col span="12">
                <FormItem label="模板名称" prop="name">
                  <Input
                    :disabled="isDisabled"
                    :maxlength="20"
                    placeholder="请输入"
                    v-model="formTmpl.name"
                  ></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="模板类型" prop="typecode">
                  <Select :disabled="isDisabled" placeholder="请选择" v-model="formTmpl.typecode">
                    <Option
                      :key="index + 1"
                      :value="index + 1"
                      v-for="(item,index) in tmplTypeArr"
                    >{{ item }}</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="8">
              <Col span="12">
                <FormItem label="计算日期" prop="calcDate">
                  <Select :disabled="isDisabled" placeholder="请选择" v-model="formTmpl.calcDate">
                    <Option
                      :key="index + 1"
                      :value="index + 1"
                      v-for="(item,index) in calcDateArr"
                    >{{ item }}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem class="long-label" label="模板生效日期" prop="modelStartDate">
                  <DatePicker
                    :disabled="isDisabled"
                    :editable="false"
                    :options="dateLimit"
                    placeholder="请选择"
                    placement="bottom-start"
                    style="width:100%"
                    type="date"
                    v-model="formTmpl.modelStartDate"
                  ></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <FormItem>
                  <div v-show="showPeopleConfig">
                    <Button @click="handleConfig" ghost type="primary">当前人员配置</Button>
                    <div :class="{'sure-hide':showSure}">
                      <Modal
                        :mask-closable="false"
                        :styles="{width: '750px'}"
                        @on-ok="hangledSelectedPeople"
                        class-name="cancle-hide"
                        v-model="modalConfig"
                      >
                        <Row :gutter="16" justify="space-between" type="flex">
                          <Col span="8">
                            <h5 class="title_inner-style1">新增关联座席</h5>
                            <div class="index-selected">
                              <Scroll height="400">
                                <Tree
                                  :data="initTreeData"
                                  :load-data="loadData"
                                  @on-check-change="getNodes"
                                  class="tree-set"
                                  ref="treeModel"
                                  show-checkbox
                                ></Tree>
                              </Scroll>
                            </div>
                          </Col>
                          <Col span="16">
                            <h5 class="title_inner-style1">已选用户</h5>
                            <div class="index-selected">
                              <Scroll height="400">
                                <Tag
                                  :key="index"
                                  :name="item.key"
                                  @on-close="handleClose"
                                  closable
                                  color="primary"
                                  type="border"
                                  v-for="(item,index) in usersGroups"
                                >{{ item.title }}</Tag>
                              </Scroll>
                            </div>
                          </Col>
                        </Row>
                      </Modal>
                    </div>
                  </div>
                  <div v-show="showPeopleList">
                    <div class="index-selected">
                      <Scroll height="200">
                        <Tag
                          :key="index"
                          :name="item.key"
                          color="primary"
                          type="border"
                          v-for="(item,index) in usersGroups"
                        >{{ item.title }}</Tag>
                      </Scroll>
                    </div>
                  </div>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <FormItem label="备注" prop="remark">
                  <Input
                    :autosize="{minRows: 2,maxRows: 5}"
                    :disabled="isDisabled"
                    :maxlength="200"
                    placeholder="请输入"
                    type="textarea"
                    v-model="formTmpl.remark"
                  ></Input>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <div class="mt-set8">
                  <h5 class="title_inner-style1">自定义公式</h5>
                  <Scroll height="200" id="scrollareaIntemplate">
                    <Row align="top" class-name="dynamic_panle" type="flex">
                      <Col span="1">
                        <Button
                          @click="handleAdd"
                          class="add-item"
                          icon="md-add"
                          shape="circle"
                          size="small"
                          type="primary"
                          v-if="showAddItem"
                        ></Button>
                      </Col>
                      <Col span="23">
                        <Row
                          :gutter="8"
                          :key="item.uuid"
                          :rules="ruleDynamic"
                          align="top"
                          class="row_style-set row_split-set22"
                          type="flex"
                          v-for="(item, index) in this.formTmpl.formulalist"
                        >
                          <Col span="6">
                            <FormItem
                              :prop="'formulalist.'+index+'.itemName'"
                              :rules="ruleDynamic.itemName"
                              label="名称"
                            >
                              <Poptip
                                :content="item.itemName"
                                :trigger="showExpressModal?null:'hover'"
                                placement="top"
                                popper-class="eleForHideOnScroll"
                              >
                                <Input
                                  :disabled="isDisabled"
                                  :maxlength="20"
                                  :ref="'itemName'+index"
                                  @mouseover="handleClearPlh"
                                  placeholder="请输入"
                                  style="width:100%"
                                  v-model="item.itemName"
                                ></Input>
                              </Poptip>
                            </FormItem>
                          </Col>
                          <Col span="6">
                            <div v-show="showExpressModal">
                              <Button
                                :disabled="isDisabled"
                                @click="expressAdd(index)"
                                ghost
                                type="primary"
                              >公式</Button>
                              <Modal
                                :mask-closable="false"
                                :styles="{width: '750px'}"
                                class-name="self-express"
                                v-model="modalExpress[index]"
                              >
                                <set-expression
                                  :apiOption="indexApi"
                                  :arrExpressIdIn="arrExpressIdIn"
                                  :arrExpressIn="arrExpressIn"
                                  :isAddOption="addOption"
                                  :selectEle="sctTmpl"
                                  :showPanel="editPanel"
                                  @getExpress="handleSetExpress"
                                  @getFactorids="handleSetFactorids"
                                  @removeFactorids="removeFactorids"
                                  ref="expressCom1"
                                  selectWays="sctIndex"
                                ></set-expression>
                              </Modal>
                            </div>
                            <div v-show="!showExpressModal">
                              <Row>
                                <Poptip
                                  :content="item.formulaname ? item.formulaname.split(',').join('') : ''"
                                  :transfer="true"
                                  placement="top"
                                  popper-class="eleForHideOnScroll"
                                  trigger="hover"
                                >
                                  <Input
                                    :rows="1"
                                    :value="item.formulaname ? item.formulaname.split(',').join('') : ''"
                                    class="express_input"
                                    disabled
                                    placeholder="公式"
                                    style="width: 100%"
                                    type="textarea"
                                  />
                                </Poptip>
                              </Row>
                            </div>
                          </Col>
                          <Col span="5">
                            <FormItem
                              :prop="'formulalist.'+index+'.topLeave'"
                              :rules="ruleDynamic.topLeave"
                              label="上限"
                            >
                              <InputNumber
                                :disabled="isDisabled"
                                :max="formTmpl.typecode===1?100:100000"
                                :min="0"
                                :precision="0"
                                :ref="'topLeave'+index"
                                @mouseover="handleClearPlh"
                                number
                                placeholder="请输入"
                                style="width:100%"
                                v-model="item.topLeave"
                              ></InputNumber>
                            </FormItem>
                          </Col>
                          <Col span="5">
                            <FormItem
                              :prop="'formulalist.'+index+'.mulaType'"
                              :rules="ruleDynamic.mulaType"
                              label="加减分"
                            >
                              <Select
                                :disabled="isDisabled"
                                :ref="'mulaType'+index"
                                @on-change="handleChageMula"
                                placeholder
                                v-model="item.mulaType"
                              >
                                <Option :value="1">加分</Option>
                                <Option :value="2">减分</Option>
                              </Select>
                            </FormItem>
                          </Col>
                          <Col span="2">
                            <Button
                              @click="handleRemove(index)"
                              class="close-item"
                              icon="md-close"
                              shape="circle"
                              size="small"
                              type="primary"
                              v-if="showCloseItem"
                            ></Button>
                          </Col>
                        </Row>
                      </Col>
                    </Row>
                  </Scroll>
                </div>
              </Col>
            </Row>
          </Form>
          <div slot="footer">
            <div v-if="showFooter">
              <Button @click="handleResetAdd" v-if="showAddReset">重置</Button>
              <Button @click="handleResetEdit" v-else>重置</Button>
              <Button
                :loading="addLoading"
                @click="handleSubmitAdd"
                type="primary"
                v-if="showAddSubmit"
              >提交</Button>
              <Button :loading="confirmLoading" @click="handleSubmitEdit" type="primary" v-else>提交</Button>
            </div>
          </div>
        </Modal>
      </div>
    </Row>
    <br />
    <Table :columns="columnsDaily" :data="dataTmpl" :loading="loading" border ref="selection"></Table>
    <Page
      :current.sync="searchForm.pageNum"
      :page-size="searchForm.pageSize"
      :total="total"
      @on-change="pageChange"
      class="mt-set16"
      show-total
    />
  </div>
</template>

<script>
import AchievePieceModelAPI from '@api/common/achievePieceModel'
import AchieveIndicatorLibAPI from '@api/common/achieveIndicatorLib'
import expressJudgeTool from '@/mixin/expressJudgeTool'
import commonConfigPeople from '@/mixin/commonConfigPeople'
import setExpression from '@/views/components/set-expression/set-expression'
import { TMPL_TYPE, CALC_DATE } from '@/config/dict.js/'
import cloneDeep from 'lodash/cloneDeep'
import { format } from 'date-fns'
import dateLimit from '@/mixin/dateLimit'

export default {
  name: 'piecework-template',
  components: {
    setExpression
  },
  mixins: [expressJudgeTool, commonConfigPeople, dateLimit],
  data () {
    return {
      total: 0,
      arrExpressIn: [],
      arrExpressIdIn: [],
      isDisabled: false,
      sctTmpl: '选择指标',
      showFooter: true,
      showAddSubmit: true,
      showAddReset: true,
      showSure: true,
      showPeopleConfig: true,
      showPeopleList: false,
      searchTagetLoading: false,
      showAddItem: false,
      showCloseItem: false,
      showExpressModal: true,
      loading: false,
      confirmLoading: false,
      AchievePieceModelAPI: false,
      addLoading: false,
      viewLoading: false,
      editLoading: false,
      delLoading: false,
      resetLoading: false,
      modalTitle: '',
      modalTmpl: false,
      modalConfig: false,
      modalExpress: [false],
      editExpress: false,
      addOption: false,
      tmplTypeArr: TMPL_TYPE,
      calcDateArr: CALC_DATE,
      indexApi: AchieveIndicatorLibAPI,
      editPanel: true,
      name: '',
      searchForm: {
        pageNum: 1,
        pageSize: 10
      },
      editId: '',
      count: 0,
      num: 0,
      indexName: [],
      formulalist: [],
      usersGroups: [],
      selectCodes: [],
      libidsGroup: [],
      columnsDaily: [
        {
          title: '模板编号',
          type: 'index'
        },
        {
          title: '模板名称',
          key: 'name'
        },
        {
          title: '所属中心',
          key: 'usercenter'
        },
        {
          title: '模板生效日期',
          key: 'modelStartDate'
        },
        {
          title: '计算日期',
          key: 'calcDate'
        },
        {
          title: '模板类型',
          key: 'typecode'
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  directives: [
                    {
                      name: 'permission',
                      arg: 'view',
                      value: 'piecework-template'
                    }
                  ],
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.infoView(params.row)
                    }
                  }
                },
                '查看'
              ),
              h(
                'Button',
                {
                  directives: [
                    {
                      name: 'permission',
                      arg: 'edit',
                      value: 'piecework-template'
                    }
                  ],
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.infoEdit(params.row)
                    }
                  }
                },
                '编辑'
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定删除该行信息？'
                  },
                  on: {
                    'on-ok': () => {
                      this.infoRemove(params.row)
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      directives: [
                        {
                          name: 'permission',
                          arg: 'delete',
                          value: 'piecework-template'
                        }
                      ],
                      props: {
                        type: 'warning',
                        size: 'small'
                      }
                    },
                    '删除'
                  )
                ]
              )
            ])
          }
        }
      ],
      dataTmpl: [],
      formTmpl: {
        name: '',
        typecode: '',
        calcDate: '',
        modelStartDate: '',
        remark: '',
        formulalist: []
      },
      ruleDynamic: {
        itemName: [
          {
            required: true,
            trigger: 'blur',
            message: '不能为空'
          }
        ],
        topLeave: [
          {
            required: true,
            type: 'number',
            validator: (rule, value, callback) => {
              if (value === null || value === '') {
                callback(new Error('不能为空'))
              }
              if (this.formTmpl.typecode === 1) {
                if (value > 100) {
                  callback(new Error('最大为100'))
                }
              }
              if (this.formTmpl.typecode === 2) {
                if (value > 100000) {
                  callback(new Error('最大为100000'))
                }
              }
              callback()
            },
            min: 0
            // message: '请输入合法数值'
          }
        ],
        mulaType: [
          {
            required: true,
            type: 'number',
            trigger: 'change',
            message: '不能为空'
          }
        ]
      },
      ruleValidate: {
        name: [
          {
            required: true,
            trigger: 'blur',
            message: '不能为空'
          }
        ],
        typecode: [
          {
            required: true,
            type: 'number',
            trigger: 'change',
            message: '请选择'
          }
        ],
        calcDate: [
          {
            required: true,
            type: 'number',
            trigger: 'change',
            message: '请选择'
          }
        ],
        modelStartDate: [
          {
            required: true,
            message: '请选择'
          }
        ]
      },
      initTreeData: []
    }
  },
  watch: {
    modalTmpl (newVal) {
      if (!newVal) {
        this.arrExpressIn = []
        this.arrExpressIdIn = []
      }
    },
    name () {
      this.searchForm.name = this.name
    }
  },
  mounted () {
    this.doInitSearch()
    let scroll = document.getElementById('scrollareaIntemplate')
    let dom = scroll.querySelector('.ivu-scroll-container')
    dom.onmousewheel = () => {
      let poptips = document.querySelectorAll('.eleForHideOnScroll')
      for (let i = 0; i < poptips.length; i++) {
        poptips[i].style.display = 'none'
      }
    }
  },
  methods: {
    restPage () {
      this.searchForm.pageNum = 1
    },
    handleClearPlh (e) {
      this.$nextTick(() => {
        e.target.focus()
      })
    },
    doInitSearch () {
      this.searchForm.pageNum = 1
      this.doSearch()
    },
    // 查询
    doSearch () {
      this.loading = true
      this.$nextTick(() => {
        AchievePieceModelAPI.viewList({ ...this.searchForm })
          .then(({ data }) => {
            this.loading = false
            if (data.status === 'success') {
              this.total = data.data.total
              const formData = cloneDeep(data.data.list)
              for (let i = 0, len = formData.length; i < len; i++) {
                formData[i].typecode = formData[i].map.typeCode
                formData[i].usercenter = formData[i].map.usercenter
                formData[i].calcDate = formData[i].map.calcDate
                formData[i].modelStartDate = format(
                  formData[i].modelStartDate,
                  this.$config.DATE_FORMAT
                )
              }
              this.dataTmpl = formData
            }
          })
          .catch(err => {
            console.error('err: ', err)
            this.loading = false
          })
      })
    },
    // 自定义公式-打开
    expressAdd (index) {
      this.num = index
      this.$set(this.modalExpress, index, true)
      // console.log(this.formTmpl)
      // if (
      //   this.$refs.expressCom1[index].arrExpress.length === 0 &&
      //   this.editExpress
      // ) {
      //   this.$refs.expressCom1[index].arrExpress = this.arrExpressIn
      //   this.$refs.expressCom1[index].arrExpressId = this.arrExpressIdIn
      // }

      if (this.formTmpl.formulalist[index].formula) {
        let tmp = this.formTmpl.formulalist[index].formula.split(',')
        this.$refs.expressCom1[index].arrExpressId = tmp
      }
      if (this.formTmpl.formulalist[index].formulaname) {
        let tmp = this.formTmpl.formulalist[index].formulaname.split(',')
        this.$refs.expressCom1[index].arrExpress = tmp
        this.$refs.expressCom1[index].expressionChina = tmp.join('')
      }
    },
    // 自定义公式-增加操作项
    handleAdd () {
      this.count++
      this.num++
      this.editExpress = false
      this.modalExpress.push(false)
      // this.$refs.expressCom.factoridArr = []
      debugger
      this.formTmpl.formulalist.push({
        index: this.count,
        topLeave: 0
      })
    },
    // 自定义公式-删除操作项
    handleRemove (index) {
      let tmpIdsString = this.formTmpl.formulalist[index].formula
      if (tmpIdsString) {
        const factoryids = tmpIdsString.split(',')
        for (let i in factoryids) {
          let tmp = factoryids[i]
          if (tmp.charAt(0) === '#') {
            this.removeFactorids([tmp])
          }
        }
      }
      this.formTmpl.formulalist.splice(index, 1)
      this.modalExpress.pop()
      this.count--
      this.num--
    },
    // 新增
    infoAdd (index) {
      this.modalTmpl = true
      this.modalTitle = '新增模板'
      this.isDisabled = false
      this.editPanel = true
      this.showFooter = true
      this.showAddSubmit = true
      this.showAddReset = true
      this.showSure = true
      this.showAddItem = true
      this.showCloseItem = true
      this.showExpressModal = true
      this.usersGroups = []
      this.initTreeData = []
      this.selectCodes = []
      this.addOption = true
      this.showPeopleConfig = true
      this.showPeopleList = false
      this.formTmpl.formulalist = [{ index: 0, topLeave: 0 }]
      this.libidsGroup = []
      this.$nextTick(() => {
        this.$refs.expressCom1.arrExpressId = []
        this.$refs.expressCom1.arrExpress = []
        this.$refs.expressCom1.factoridArr = []
        this.$refs['formTmpl'].resetFields()
      })

      if (this.$refs.expressCom1) {
        this.$refs.expressCom1.expression = ''
      }
    },
    handleChageMula (val) {
      console.log(typeof val)
    },
    // 表格操作-查看
    infoView (row) {
      let infoId = row.uuid
      this.viewLoading = true
      this.modalTitle = '查看模板'
      AchievePieceModelAPI.view(infoId)
        .then(({ data }) => {
          this.viewLoading = false
          if (data.status === 'success') {
            this.modalTmpl = true
            this.isDisabled = true // 指标是否可编辑
            this.showFooter = false // 是否显示底部操作按钮
            this.showSure = false // 是否显示确定按钮
            this.showPeopleConfig = false // 已选按钮是否可关闭
            this.showPeopleList = true
            this.showAddItem = false // 是否显示打分标准-添加按钮
            this.showCloseItem = false // 是否显示打分标准-关闭按钮
            this.showExpressModal = false
            this.editExpress = false
            this.addOption = false
            console.log(data.data)
            for (let n = 0, len = data.data.formulalist.length; n < len; n++) {
              if (data.data.formulalist[n].formulaname) {
                this.arrExpressIn = data.data.formulalist[n].formulaname.split(
                  ','
                )
              }
            }
            const formDataView = cloneDeep(data.data)
            formDataView.modelStartDate = format(
              formDataView.map.modelStartDate,
              this.$config.DATE_FORMAT
            )

            this.editPanel = false // 是否显示 设置公式面板
            this.usersGroups = []
            if (formDataView.map.usernames) {
              for (
                let i = 0, len = formDataView.map.usernames.split(',').length;
                i < len;
                i++
              ) {
                this.usersGroups.push({
                  title: formDataView.map.usernames.split(',')[i],
                  key: formDataView.usercodes.split(',')[i]
                })
              }
            }

            formDataView.formulalist = [].concat(formDataView.formulalist)
            this.$refs['formTmpl'].resetFields()
            this.formTmpl = formDataView
          }
        })
        .catch(err => {
          console.error(err)
          this.viewLoading = false
        })
    },
    // 表格操作-编辑
    infoEdit (row) {
      let infoId = row.uuid
      this.editId = row.uuid
      this.editLoading = true
      this.modalTitle = '编辑模板'
      AchievePieceModelAPI.view(infoId)
        .then(({ data }) => {
          this.editLoading = false
          if (data.status === 'success') {
            this.modalTmpl = true
            this.isDisabled = false
            this.showFooter = true
            this.showAddSubmit = false
            this.showAddReset = false
            this.showSure = true
            this.showPeopleConfig = true
            this.showPeopleList = false
            this.showAddItem = true
            this.showCloseItem = true
            this.showExpressModal = true
            this.editExpress = true
            this.initTreeData = []
            this.selectCodes = []
            this.addOption = false
            this.count = data.data.formulalist.length - 1
            this.num = data.data.formulalist.length - 1
            if (data.data.libids) {
              this.libidsGroup = data.data.libids.split(',')
            }
            if (data.data.usercodes) {
              this.selectCodes = data.data.usercodes.split(',')
            }
            for (let n = 0, len = data.data.formulalist.length; n < len; n++) {
              if (
                data.data.formulalist[n].formulaname &&
                data.data.formulalist[n].formula
              ) {
                this.arrExpressIn = data.data.formulalist[n].formulaname.split(
                  ','
                )
                this.arrExpressIdIn = data.data.formulalist[n].formula.split(
                  ','
                )
              }
            }
            const formDataView = cloneDeep(data.data)
            formDataView.modelStartDate = format(
              formDataView.map.modelStartDate,
              this.$config.DATE_FORMAT
            )
            this.editPanel = true
            this.usersGroups = []
            if (formDataView.map.usernames) {
              for (
                let i = 0, len = formDataView.map.usernames.split(',').length;
                i < len;
                i++
              ) {
                this.usersGroups.push({
                  title: formDataView.map.usernames.split(',')[i],
                  key: formDataView.usercodes.split(',')[i]
                })
              }
            }
            formDataView.formulalist = [].concat(formDataView.formulalist)
            this.$nextTick(() => {
              let m = 0
              for (let len = formDataView.formulalist.length; m < len; m++) {
                let tmp = formDataView.formulalist[m].formulaname
                  .split(',')
                  .join('')
                this.$refs.expressCom1[m].expressionChina = tmp
              }
            })
            this.$refs['formTmpl'].resetFields()
            this.formTmpl = formDataView
          }
        })
        .catch(err => {
          console.error(err)
          this.editLoading = false
        })
    },
    // 表格操作-删除
    infoRemove (row) {
      let infoId = row.uuid
      this.delLoading = true
      AchievePieceModelAPI.delete(infoId)
        .then(({ data }) => {
          this.delLoading = false
          if (data.status === 'success') {
            this.$Message.destroy()
            this.$Message.success('删除成功!')
            this.doInitSearch()
          }
        })
        .catch(err => {
          console.error('err: ', err)
          this.delLoading = false
        })
    },
    // 新增模板-提交
    handleSubmitAdd () {
      this.formTmpl.libids = this.libidsGroup.join(',')
      this.$refs['formTmpl'].validate(valid => {
        if (valid) {
          this.addLoading = true
          const formData = cloneDeep(this.formTmpl)
          formData.map = {
            modelStartDate: format(
              formData.modelStartDate,
              this.$config.DATE_FORMAT
            )
          }

          delete formData.modelStartDate
          if (formData.formulalist.length === 0) {
            this.addLoading = false
            this.$Message.destroy()
            this.$Message.warning('请设置公式!')
            return false
          } else {
            for (let i = 0, len = formData.formulalist.length; i < len; i++) {
              if (!formData.formulalist[i].formula) {
                this.addLoading = false
                this.$Message.destroy()
                this.$Message.warning('请设置公式!')
                return false
              }
              if (!this.isCorrectExpress(this.selectedFactorIdsArr)) {
                formData.formulalist[i].formula = ''
                formData.formulalist[i].formulaname = ''
                this.addLoading = false
                this.$Message.destroy()
                this.$Message.warning('输入的公式格式有误，请重新输入!')
                return false
              }
            }
          }

          if (this.usersGroups.length === 0) {
            this.$Message.destroy()
            this.$Message.warning('请先进行人员配置!')
            this.addLoading = false
            return false
          }
          AchievePieceModelAPI.create({ ...formData })
            .then(({ data }) => {
              this.addLoading = false
              if (data.status === 'success') {
                this.modalTmpl = false
                this.$refs['formTmpl'].resetFields()
                this.usersGroups = []
                this.$Message.destroy()
                this.$Message.success('添加成功!')
                this.doInitSearch()
              }
            })
            .catch(err => {
              console.error(err)
              this.addLoading = false
            })
        }
      })
    },
    // 编辑模板-提交
    handleSubmitEdit () {
      this.formTmpl.libids = this.libidsGroup.join(',')
      this.$refs['formTmpl'].validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const formDataEdit = cloneDeep(this.formTmpl)
          formDataEdit.map = {
            modelStartDate: format(
              formDataEdit.modelStartDate,
              this.$config.DATE_FORMAT
            )
          }

          if (this.usersGroups.length === 0) {
            this.$Message.destroy()
            this.$Message.warning('请先进行人员配置!')
            this.confirmLoading = false
            return false
          }
          if (formDataEdit.formulalist.length === 0) {
            this.confirmLoading = false
            this.$Message.destroy()
            this.$Message.warning('请设置公式!')
            return false
          } else {
            for (
              let i = 0, len = formDataEdit.formulalist.length;
              i < len;
              i++
            ) {
              if (!formDataEdit.formulalist[i].formula) {
                this.confirmLoading = false
                this.$Message.destroy()
                this.$Message.warning('请设置公式!')
                return false
              }
              if (
                !this.isCorrectExpress(
                  formDataEdit.formulalist[i].formula.split(',')
                )
              ) {
                formDataEdit.formulalist[i].formula = ''
                formDataEdit.formulalist[i].formulaname = ''
                this.confirmLoading = false
                this.$Message.destroy()
                this.$Message.warning('输入的公式格式有误，请重新输入!')
                return false
              }
            }
          }
          delete formDataEdit.modelStartDate
          AchievePieceModelAPI.edit({ ...formDataEdit })
            .then(({ data }) => {
              this.confirmLoading = false
              if (data.status === 'success') {
                this.modalTmpl = false
                this.$refs['formTmpl'].resetFields()
                this.$Message.destroy()
                this.$Message.success('编辑成功!')
                this.doInitSearch()
              }
            })
            .catch(err => {
              console.error(err)
              this.confirmLoading = false
            })
        }
      })
    },
    // 新增模板-重置
    handleResetAdd () {
      this.$refs['formTmpl'].resetFields()
      this.$nextTick(() => {
        for (let m = 0, len = this.formTmpl.formulalist.length; m < len; m++) {
          this.$refs['itemName' + m][0].$el.children[1].value = ''
          this.$refs['topLeave' + m][0].$el.children[1].value = ''
          this.$refs['mulaType' + m][0]._data.values = []
          this.formTmpl.formulalist[m].formula = ''
          this.formTmpl.formulalist[m].formulaname = ''
          this.$refs.expressCom1[m].expressionChina = ''
          this.$refs.expressCom1[m].arrExpress = []
          this.$refs.expressCom1[m].arrExpressId = []
          this.$refs.expressCom1[m].factoridArr = []
        }
      })
      this.initTreeData = []
      this.usersGroups = []
      this.libidsGroup = []
    },
    // 编辑模板-重置
    handleResetEdit () {
      this.resetLoading = true
      AchievePieceModelAPI.view(this.editId)
        .then(({ data }) => {
          this.resetLoading = false
          if (data.status === 'success') {
            const formDataView = cloneDeep(data.data)
            formDataView.modelStartDate = format(
              formDataView.modelStartDate,
              this.$config.DATE_FORMAT
            )
            if (data.data.libids) {
              this.libidsGroup = data.data.libids.split(',')
            }
            if (formDataView.map.usernames) {
              this.usersGroups = []
              for (
                let i = 0, len = formDataView.map.usernames.split(',').length;
                i < len;
                i++
              ) {
                this.usersGroups.push({
                  title: formDataView.map.usernames.split(',')[i],
                  key: formDataView.usercodes.split(',')[i]
                })
              }
            }
            this.$nextTick(() => {
              for (
                let m = 0, len = formDataView.formulalist.length;
                m < len;
                m++
              ) {
                let tmp = formDataView.formulalist.formulaname
                  .split(',')
                  .join('')
                this.$refs.expressCom1[m].expressionChina = tmp
              }
            })
            this.formTmpl = formDataView
          }
        })
        .catch(err => {
          console.error(err)
          this.resetLoading = false
        })
    },
    // 人员配置-确定
    hangledSelectedPeople () {
      this.teamArr = []
      this.usercodesArr = []
      this.teamGroup = []
      this.childrenData.map(item => {
        this.usercodesArr.push(item.key)
      })
      this.teamArr = this.$refs.treeModel
        .getCheckedAndIndeterminateNodes()
        .filter(item => {
          if (item.key) {
            return (
              item.key.split('_')[0] !== 'agent' &&
              item.key.split('_')[0] !== 's' &&
              item.key.split('_')[0] !== 'a'
            )
          }
        })
      this.linesArr = this.$refs.treeModel
        .getCheckedAndIndeterminateNodes()
        .filter(item => {
          if (item.key) {
            return (
              item.key.split('_')[0] !== 'agent' &&
              item.key.split('_')[0] !== 's' &&
              item.key.split('_')[0] !== 't'
            )
          }
        })
      for (let i = 0, len = this.teamArr.length; i < len; i++) {
        this.teamGroup.push(this.teamArr[i].key)
      }
      this.formTmpl.teamids = this.teamGroup.join(',')
      this.formTmpl.usercodes = this.usercodesArr.join(',')
    },
    // 公式设置
    handleSetExpress (formula, formulaname, idArray) {
      this.formTmpl.formulalist[this.num].formula = formula
      this.formTmpl.formulalist[this.num].formulaname = formulaname
      this.selectedFactorIdsArr = idArray
      console.log(this.libidsGroup)
    },
    // 指标Id
    handleSetFactorids (factorids) {
      console.log(this.libidsGroup)
      if (factorids) {
        this.libidsGroup.push(factorids)
      }
    },
    removeFactorids (idArray) {
      if (idArray) {
        for (let i in idArray) {
          var tmp = idArray[i].substring(1, idArray[i].length - 1) // 去掉‘#’
          for (let j = 0; j < this.libidsGroup.length; j++) {
            if (tmp === this.libidsGroup[j]) {
              this.libidsGroup.splice(j, 1)
              break
            }
          }
        }
      }
    },
    // 分页
    pageChange (pageNum) {
      this.searchForm.pageNum = pageNum
      this.doSearch()
    }
  }
}
</script>

<style lang="less">
.add-item {
  margin-top: 4px;
}
.close-item {
  margin-top: 4px;
}
.cancle-hide .ivu-modal-footer button:first-child {
  display: none;
}
.sure-hide .ivu-modal-footer {
  display: none;
}
.row_style-set .ivu-form-item {
  margin-bottom: 0;
}
.mg-set {
  margin: 0 12px 0 8px;
}
.long-label {
  .ivu-form-item-label {
    width: 96px !important;
  }
  .ivu-form-item-content {
    margin-left: 96px !important;
  }
}
.index-selected {
  margin-top: 16px;
  padding-left: 8px;
  border: 1px solid #dcdee2;
  border-radius: 2px;
}
.row_split-set22 {
  margin-bottom: 22px;
}
.self-express .ivu-modal-footer .ivu-btn:first-child {
  display: none;
}
</style>
<style lang="less" scoped>
/deep/.ivu-scroll-container {
  overflow-y: auto;
  overflow-x: hidden;
}
/deep/.tree-set > .ivu-tree-children > li > .ivu-checkbox-wrapper {
  pointer-events: none;
}
</style>
