<template>
  <q-card class="q-px-md" style="width:600px;">
    <q-card-section class="row items-center q-pb-none">
      <div class="text-h6">
        <span>关联系统数据模板</span>
      </div>
      <q-space />
      <q-btn icon="close" flat round dense v-close-popup />
    </q-card-section>
    <q-card-section>
      <q-banner
        rounded
        class="bg-orange-2 text-black q-py-none q-px-md q-mb-md"
        style="min-height:30px;"
      >
        <div class="row items-center">
          <span class="q-mr-md">
            <inline-svg
              class="svg-icon svg-icon-orange"
              src="icons/svg/Code/Warning-2.svg"
            ></inline-svg>
          </span>
          <span style="font-size:12px;"
            >关联系统数据后，无法进行手动进度设置，如需手动设置进度需要取消关联</span
          >
        </div>
      </q-banner>
      <div class="text-subtitle2 text-weight-bold q-mt-md">
        <span>模板选择</span>
      </div>
      <div class="q-mt-xs">
        <q-select
          filled
          v-model="chosenRule"
          :options="tempsList"
          option-value="Id"
          option-label="RuleName"
          dense
          options-selected-class="text-deep-orange"
          :rules="[val => !!val || '请选择规则模板']"
          ref="tempchosen"
        >
          <template v-slot:option="scope">
            <q-item v-bind="scope.itemProps" v-on="scope.itemEvents">
              <q-item-section avatar>
                <q-avatar size="40px;" rounded color="green-1">
                  <span class="text-light-green">{{
                    scope.opt.RuleName.substring(0, 1)
                  }}</span>
                </q-avatar>
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ scope.opt.RuleName }}</q-item-label>
                <q-item-label caption>{{ scope.opt.Remark }}</q-item-label>
              </q-item-section>
            </q-item>
          </template>
        </q-select>
      </div>
      <div class="text-subtitle2 text-weight-bold q-mt-md">
        <span>关键值设定</span>
      </div>
      <div class="flex row items-start q-mt-xs">
        <q-input
          dense
          standout
          behavior="menu"
          v-model="initTarget"
          label="起始值"
          mask="#.##"
          fill-mask="0"
          reverse-fill-mask
          class="q-mr-xs col"
        />
        <q-input
          dense
          standout
          behavior="menu"
          v-model="maxTarget"
          ref="maxTarget"
          label="目标值"
          mask="#.##"
          fill-mask="0"
          reverse-fill-mask
          class="q-ml-xs col"
          :rules="[
            val =>
              !(Number.parseFloat(initTarget) >= Number.parseFloat(val)) ||
              '目标值不能小于或等于初始值'
          ]"
        />
      </div>
      <div class="text-subtitle2 text-weight-bold q-mt-md">
        <span>关联部门/人员</span>
      </div>
      <div class="flex row q-mt-xs">
        <div class="q-mr-md">
          <q-select
            dense
            standout
            behavior="menu"
            :options="groupData"
            option-label="name"
            option-value="id"
            v-model="defaultGroupType"
          ></q-select>
        </div>
        <div class="col relative-position">
          <q-input
            standout
            bottom-slots
            v-model="searchText"
            placeholder="输入你需要搜索的内容"
            dense
            @input="querySearch"
          >
            <template v-slot:append>
              <inline-svg
                class="svg-icon svg-icon-primary"
                src="icons/svg/General/Search.svg"
              ></inline-svg>
            </template>
          </q-input>
          <div
            style="width:100%;margin-top:45px;max-height:300px;"
            class="bg-grey-1 q-py-xs absolute-top-left shadow-3 rounded-borders scroll myscroll"
            v-if="showResult"
          >
            <q-list>
              <q-item
                class="rounded-borders"
                clickable
                v-ripple
                v-for="(x, i) in resultsList"
                :key="i"
                @click="createRange(x)"
              >
                <q-item-section avatar>
                  <q-avatar
                    style="background-color: #F3F6F9;"
                    rounded
                    size="40px"
                    text-color="secondary"
                  >
                    <img :src="x.icon" v-if="x.icon" />
                    <span v-else>{{ x.name.substring(0, 1) }}</span>
                  </q-avatar>
                </q-item-section>
                <q-item-section>
                  <q-item-label class="font-pfb">{{ x.name }}</q-item-label>
                  <q-item-label caption class="remark-font">
                    <span>{{
                      x.type == 2 ? `${x.deptName}·${x.postName}` : "部门"
                    }}</span>
                  </q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
            <div
              class="q-py-lg remark-font text-center"
              v-if="!resultsList || resultsList.length == 0"
            >
              未找到数据，对方或不是你的{{ defaultGroupType.name }}
            </div>
          </div>
        </div>
      </div>
      <div class=" scroll" style="height:200px">
        <div class="row items-center">
          <q-avatar rounded color="primary" size="36px">
            <inline-svg
              class="svg-icon svg-icon-white"
              src="icons/svg/Code/Git4.svg"
            ></inline-svg>
          </q-avatar>
          <div class="text-subtitle2 col q-mx-md">
            <div>我自己</div>
            <div class="remark-font">
              使用模板系统会强制将用户设定为第一统计对象，此处无法修改
            </div>
          </div>
        </div>
        <div
          class="row items-center q-mt-md"
          v-for="(x, i) in rangeList"
          :key="i"
        >
          <q-avatar
            style="background-color: #F3F6F9;"
            rounded
            size="40px"
            text-color="secondary"
            v-if="x.type == 2"
          >
            <img :src="x.icon" v-if="x.icon" />
            <span v-else>{{ x.name.substring(0, 1) }}</span>
          </q-avatar>
          <q-avatar
            rounded
            size="40px"
            text-color="warning"
            color="orange-1"
            v-if="x.type == 1"
          >
            <span>{{ x.name.substring(0, 1) }}</span>
          </q-avatar>
          <div class="text-subtitle2 col q-mx-md">
            <div>{{ x.name }}</div>
            <div class="remark-font">
              {{ x.type == 2 ? `${x.deptName}·${x.postName}` : "部门" }}
            </div>
          </div>
          <div class="row" style="height:20px;">
            <span title="删除" @click="deleteRange(i)">
              <inline-svg
                class="svg-icon svg-icon-g-p"
                src="icons/svg/General/Trash.svg"
                width="20px"
                height="20px"
              ></inline-svg>
            </span>
          </div>
        </div>
      </div>
    </q-card-section>
    <q-card-actions align="right">
      <div>
        <q-btn flat label="取消" color="primary q-mr-md" v-close-popup />
        <q-btn label="保存" color="primary" @click="saveRange" />
      </div>
    </q-card-actions>
  </q-card>
</template>

<script>
import {
  queryKRRuleList,
  queryMyManageDepartment,
  queryMyChildEmployeeList,
  setKRRule,
  queryKRRuleRangeList
} from "../../api/okr/work";
import { mapGetters } from "vuex";
export default {
  props: ["kr", "period"],
  computed: {
    ...mapGetters(["userInfo"])
  },
  data() {
    return {
      tempsList: [],
      chosenRule: null,
      defaultGroupType: {},
      groupData: [
        {
          id: 1,
          name: "直系下属"
        },
        {
          id: 2,
          name: "下级部门"
        }
      ],
      deptsList: [],
      usersList: [],
      resultsList: [],
      showResult: false,
      searchText: "",
      rangeList: [],
      initTarget: "0.00",
      maxTarget: "0.00"
    };
  },
  created() {
    this.defaultGroupType = this.groupData[0];
    if (this.kr.RuleId != 0) {
      this.initTarget = this.kr.StartValue.toFixed(2);
      this.maxTarget = this.kr.EndValue.toFixed(2);
    }
    this.queryRules();
  },
  mounted() {
    if (this.kr.RuleId != 0) {
      setTimeout(() => {
        this.queryRangeList();
      }, 1000);
    }
  },
  methods: {
    saveRange() {
      this.$refs.tempchosen.validate();
      this.$refs.maxTarget.validate();
      if (!this.$refs.tempchosen.hasError && !this.$refs.maxTarget.hasError) {
        let obj = {
          Id: this.kr.Id,
          RuleId: this.chosenRule.Id,
          RuleSTime: this.period.StartDate,
          RuleETime: this.period.EndDate,
          StartValue: this.initTarget,
          EndValue: this.maxTarget,
          RelationList: [
            {
              Type: 2,
              RelationId: this.userInfo.Id
            }
          ]
        };
        this.rangeList.forEach(x => {
          obj.RelationList.push({
            Type: x.type,
            RelationId: x.id
          });
        });
        setKRRule(obj).then(r => {
          this.$emit("save");
        });
      }
    },
    deleteRange(i) {
      this.rangeList.splice(i, 1);
    },
    createRange(obj) {
      let range = this.rangeList.find(x => {
        if (x.id == obj.id && x.type == obj.type) {
          return x;
        }
      });
      if (!range || !range.id) {
        this.rangeList.unshift(obj);
      }
      this.searchText = "";
      this.showResult = false;
    },
    queryRules() {
      queryKRRuleList({}).then(r => {
        this.tempsList = r.Data;
        if (this.kr.RuleId > 0) {
          this.tempsList.forEach(x => {
            if (x.Id == this.kr.RuleId) {
              this.chosenRule = x;
            }
          });
        }
        this.queryMyDepat();
      });
    },
    queryMyDepat() {
      queryMyManageDepartment({}).then(r => {
        this.queryUsers();
        this.deptsList = r.Data;
      });
    },
    queryUsers() {
      queryMyChildEmployeeList({}).then(r => {
        this.usersList = r.Data;
      });
    },
    querySearch() {
      this.searchText = this.searchText.trim();
      let reg = /[0-9]+/g;
      this.searchText = this.searchText.replace(reg, "");
      if (this.searchText != "") {
        this.resultsList = [];
        if (this.defaultGroupType.id == 1) {
          this.usersList.forEach(x => {
            if (x.EmployeeName.indexOf(this.searchText) != -1) {
              this.resultsList.push({
                id: x.Id,
                name: x.EmployeeName,
                type: 1,
                icon: x.UserIcon,
                deptName: x.DeptName,
                postName: x.PostName
              });
            }
          });
        } else if (this.defaultGroupType.id == 2) {
          this.deptsList.forEach(x => {
            this.searchDepartment(x);
          });
        }
        this.showResult = true;
      } else {
        this.showResult = false;
      }
    },
    searchDepartment(obj) {
      if (obj.DeptName.indexOf(this.searchText) != -1) {
        this.resultsList.push({
          id: obj.DeptId,
          name: obj.DeptName,
          type: 1
        });
      }
      if (obj.ChildList && obj.ChildList.length > 0) {
        obj.ChildList.forEach(x => {
          this.searchDepartment(x);
        });
      }
    },
    queryRangeList() {
      queryKRRuleRangeList({
        KeyResultId: this.kr.Id
      }).then(r => {
        r.Data.forEach(x => {
          if (x.Type == 2 && x.RelationId != this.userInfo.Id) {
            this.rangeList.push({
              id: x.RelationId,
              name: x.RelationName,
              type: 2,
              icon: x.UserIcon,
              deptName: x.DeptName,
              postName: x.PostName
            });
          } else if (x.Type == 1) {
            this.rangeList.push({
              id: x.RelationId,
              name: x.RelationName,
              type: 1
            });
          }
        });
      });
    }
  }
};
</script>

<style></style>
