<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :append-to-body="false"
    :close-on-click-modal="false"
    width="100%"
    :before-close="cancel"
    :maxable="true"
    :resizable="true"
  >
    <el-form
      ref="form"
      :rules="rules"
      class="el-form-box"
      :model="form"
      label-width="120px"
    >
      <el-row :gutter="15">
        <el-col :span="4">
          <headerTitle title="基本信息"></headerTitle>
          <el-row>
            <el-col :span="24">
              <el-form-item label="编码" prop="code">
                <el-input v-model="form.code" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="类型" prop="type">
                <el-select
                  v-model="form.type"
                  clearable
                  style="width: 100%"
                  @change="typeChange"
                >
                  <el-option label="年度" :value="1"></el-option>
                  <el-option label="季度" :value="2"></el-option>
                  <el-option label="月度" :value="3"></el-option>
                  <!-- <el-option label="周" :value="2"></el-option> -->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="目标对象" prop="assessmentObject">
                <el-select
                  v-model="form.assessmentObject"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="公司" :value="1"></el-option>
                  <el-option label="部门" :value="2"></el-option>
                  <el-option label="个人" :value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :span="24"
              v-if="form.assessmentObject == 2 || form.assessmentObject == 3"
            >
              <el-form-item label="部门" prop="departmentId">
                <deptSelect
                  :disabled="title == '详情'"
                  v-model="form.departmentId"
                  @changeGroup="searchDeptNodeClick"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.assessmentObject == 3">
              <el-form-item label="姓名" prop="userId">
                <el-select
                  :disabled="title == '详情'"
                  v-model="form.userId"
                  @change="changeExecutor"
                  size="small"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="item in executorList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="统计财年" prop="assessmentDimensions">
                <el-date-picker
                  type="years"
                  style="width: 100%"
                  v-model="form.assessmentDimensions"
                  placeholder="选择一个或多个年"
                  format="yyyy"
                  value-format="yyyy"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="起始月份" prop="assessmentCycle">
                <el-select
                  v-model="form.assessmentCycle"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="1月" :value="1"></el-option>
                  <el-option label="2月" :value="2"></el-option>
                  <el-option label="3月" :value="3"></el-option>
                  <el-option label="4月" :value="4"></el-option>
                  <el-option label="5月" :value="5"></el-option>
                  <el-option label="6月" :value="6"></el-option>
                  <el-option label="7月" :value="7"></el-option>
                  <el-option label="8月" :value="8"></el-option>
                  <el-option label="9月" :value="9"></el-option>
                  <el-option label="10月" :value="10"></el-option>
                  <el-option label="11月" :value="11"></el-option>
                  <el-option label="12月" :value="12"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="负责人" prop="superintendentName">
                <el-input
                  v-model="form.superintendentName"
                  @click.native="userListOpen"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="可见人" prop="participantsName">
                <el-input
                  v-model="participantsName"
                  @click.native="receptionUserOpen"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="describes">
                <el-input v-model="form.describes" type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="20">
          <headerTitle title="目标"></headerTitle>
          <!-- <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane
          :label="item.name"
          :name="item.name"
          v-for="item in salesRegulationList"
          :key="item.name"
        >
         
        </el-tab-pane>
      </el-tabs> -->
          <vue2-org-tree
            name="test"
            :data="treeData"
            :collapsable="true"
            :render-content="renderContent"
            horizontal="horizontal"
            @on-expand="onExpand"
            ref="testRef"
          />
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="handleSave(0)" v-click-once
        >保存</el-button
      >
      <el-button @click="cancel">返回</el-button>
    </div>
    <staffSelection
      ref="staffSelectionRef"
      @confirm="staffSelectionbk"
    ></staffSelection>
    <UserList ref="userListRef" @success="userListSuccess"></UserList>
  </ele-modal>
</template>
<script>
const defForm = {
  name: '', //名称
  targetDefinitionList: [], //目标规则
  assessmentObject: '', // //考核对象 1公司 2部门 3个人
  assessmentDimensions: [], //统计财年
  assessmentCycle: '', //起始月份
  departmentId: '', //部门id
  departmentName: '', //部门名称
  userId: '', //用户id
  userName: '', //用户名称
  superintendentId: '', //负责人id
  superintendentName: '', //负责人名称
  participantsId: '',
  participantsName: '',
  discernibleUserList: [],
  status: '',
  type: 1,
  describes: ''
};
import {
  targetDefinitionPage,
  salesTargetSave,getById
} from '@/api/targetManage/index.js';
import {
  getTargetManageTree,
  renderInput,
  renderSelect
} from '@/views/targetManage/util.js';
import deptSelect from '@/components/CommomSelect/dept-select.vue';
import { getUserPage } from '@/api/system/organization';
import dictMixins from '@/mixins/dictMixins';
import staffSelection from '@/views/marketManagem/components/staffSelection.vue';
import UserList from '@/views/marketManagem/components/userList.vue';

export default {
  components: { deptSelect, staffSelection, UserList },
  mixins: [dictMixins],
  computed: {},
  data() {
    return {
      dialogType: '',
      fullscreen: false,
      title: '',
      participantsName: '',
      unitOption: [],
      addOrEditDialogFlag: false,
      activeName: '',
      treeData: { label: '销售目标', children: [], expand: true },
      form: { ...defForm },
      flatData: [],
      executorList: [],
      salesRegulationList: [],
      targetDefinitionList: [],
      rules: {
        type: { required: true, message: '请选择', trigger: 'change' },
        assessmentDimensions: {
          required: true,
          message: '请选择',
          trigger: 'change'
        },
        assessmentCycle: {
          required: true,
          message: '请选择',
          trigger: 'change'
        },
        assessmentObject: {
          required: true,
          message: '请选择',
          trigger: 'change'
        },
        departmentId: { required: true, message: '请选择', trigger: 'change' },
        userId: { required: true, message: '请选择', trigger: 'change' },
        name: { required: true, message: '请输入', trigger: 'change' }
      }
    };
  },
  mounted() {},
  created() {},
  methods: {
    renderContent(h, data) {
      return (
        <div class={!data.type ? 'treeItem1 treeItem' : 'treeItem'}>
          <span class="label">{data.label}</span>
          {data.type != 1
            ? renderInput(
                h,
                data,
                'ratioInput',
                '占比',
                this.form,
                this.treeData.children
              )
            : ''}
          {renderInput(
            h,
            data,
            'valueInput',
            '目标值',
            this.form,
            this.treeData.children
          )}
          {renderSelect(
            h,
            data,
            this.form,
            this.treeData.children,
            this.unitOption
          )}
        </div>
      );
    },

    //初始化
    async open(row = {}, type) {
      const data = await targetDefinitionPage({
        pageNum: 1,
        size: 100
      });

      this.unitOption = await this.requestDict('流程实例的结果');
      console.log(this.unitOption, 'this.unitOption');
      this.targetDefinitionList = data.list;
      this.addOrEditDialogFlag = true;
      this.title = type == 'add' ? '新增' : '修改';
      this.dialogType = type;
      if (type !== 'add') {
      this.form = await getById(row.id);
        if (this.form.departmentId) {
          this.getUserList({ groupId: this.form.departmentId });
        }
        if (this.form.discernibleUserList) {
          this.participantsName = this.form.discernibleUserList
            .map((item) => item.name)
            .toString();
        }

        this.form.assessmentDimensions =
          this.form.assessmentDimensions.split(',');
        this.treeData.children = this.form.targetDefinitionList;
      } else {
        this.initTree();
      }
    },
    receptionUserOpen() {
      this.$refs.staffSelectionRef.open(this.form.participantsId || []);
    },
    staffSelectionbk(data) {
      this.form.discernibleUserList = data;
      this.participantsName = data.map((item) => item.name).toString();
      // console.log(data,'data')
    },
    userListOpen(key) {
      this.$refs.userListRef.open(key);
    },
    userListSuccess({ data }) {
      this.form.superintendentName = data?.name;
      this.form.superintendentId = data?.id;
    },
    //tree更新
    initTree() {
      this.treeData.children = [];
      this.targetDefinitionList.forEach((item) => {
        this.treeData.children.push(getTargetManageTree(item, this.form.type));
      });
    },
    onExpand(e, data) {
      if ('expand' in data) {
        data.expand = !data.expand;
        if (!data.expand && data.children) {
          this.collapse(data.children);
        }
      } else {
        this.$set(data, 'expand', true);
      }
    },
    collapse(list) {
      var _this = this;
      list.forEach(function (child) {
        if (child.expand) {
          child.expand = false;
        }
        child.children && _this.collapse(child.children);
      });
    },
    //选择部门(搜索)
    searchDeptNodeClick(info, row) {
      this.form.userId = '';
      this.form.userName = '';
      if (info) {
        const params = { groupId: info };
        this.getUserList(params);
        this.form.departmentName = row.name;
      } else {
        this.form.executeGroupId = null;
      }
    },
    // 获取审核人列表、巡点检人员
    async getUserList(params) {
      try {
        let data = { pageNum: 1, size: -1 };
        // 如果传了参数就是获取巡点检人员数据
        if (params) {
          data = Object.assign(data, params);
        }
        const res = await getUserPage(data);
        this.executorList = res.list;
      } catch (error) {}
    },
    // 执行人选择
    changeExecutor(val) {
      if (val) {
        this.form.userId = val;
        this.form.userName = this.executorList.filter(
          (item) => item.id === val
        )[0].name;
      }
    },

    typeChange() {
      this.initTree();
    },
    handleClick() {},
    handleSave(flag) {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return this.$message.warning('有必填项未填，请检查');
        this.form.targetDefinitionList = this.treeData.children;
        this.form.assessmentDimensions =
          this.form.assessmentDimensions.toString();
        if (
          this.form.assessmentObject == 1 ||
          this.form.assessmentObject == 2
        ) {
          this.form.userId = '';
          this.form.userName = '';
        }
        if (this.form.assessmentObject == 1) {
          this.form.departmentId = '';
          this.form.departmentName = '';
        }
        const id = await salesTargetSave(this.form);
        if (flag) {
          await this.handleSub(id);
        }
        this.$message.success('操作成功');
        this.done();
        this.cancel();
      });
    },
    //提交-开启流程
    async handleSub(id) {
      try {
        await settlementAccountSubmit({ businessId: id });
      } catch (e) {
        this.$message.error(e.message);
      }
    },
    //刷新主列表数据
    done() {
      this.$emit('reload');
    },
    //关闭弹窗
    cancel() {
      this.addOrEditDialogFlag = false;
      this.form = {
        ...defForm
      };
    }
  }
};
</script>
<style scoped lang="scss">
@import '~vue2-org-tree/dist/style.css';
:deep(.treeItem1) {
  padding: 15px 15px !important;
  color: #3942a7;
  background: url(../../../../assets/main_item.png);
  background-size: cover;
  .label {
    font-size: 14px;
    font-weight: bold;
  }
}
:deep(.org-tree-node-btn) {
  background-color: #bb90f5;
}
:deep(.treeItem) {
  display: flex;
  justify-content: center;
  padding: 6px 15px;
  align-items: center;
  .label {
    display: flex;
    // maxwidth: 100%;
    min-width: 80px;
    justify-content: center;
    align-items: center;
  }
  .ratioInput {
    width: 77px;
  }
  .valueInput {
    width: 105px;
  }
  .el-select {
    width: 80px;
  }
  .el-input {
    width: auto;
  }
  input {
    margin-left: 5px;
  }
  .el-input__suffix {
    line-height: 36px;
  }
}
:deep(.long-dialog-form .el-dialog__body) {
  min-height: 700px;
}
:deep(.org-tree-node-label .org-tree-node-label-inner) {
  padding: 0;
}
:deep(
    .horizontal .org-tree-node.collapsed,
    .horizontal .org-tree-node.is-leaf
  ) {
  padding-bottom: 5px;
  padding-top: 5px;
}
</style>