<template>
  <!-- 新建分组模板 -->
  <el-dialog
    :title="title"
    append-to-body
    :visible.sync="box"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @closed="closed"
    width="70%"
  >
    <el-form
      :model="form"
      @submit.native.prevent
      :rules="rules"
      ref="groups"
      label-position="right"
      label-width="100px"
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item title="分组信息" name="1">
          <el-form-item style="width: 400px" label="分组名称" prop="groupName">
            <el-input v-model="form.groupName" placeholder="请输入 分组名称" size="small" :disabled="loading"
                      maxlength="40"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item style="width: 400px" label="分组排序" prop="sort">
            <el-input type="number" v-model="form.sort" min="0" placeholder="请输入 分组名称"
                      size="small"></el-input>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item title="服务信息" name="2">
          <div class="scroll-row">
            <el-card class="card-row" shadow="hover" v-for="(item, index) in serveAll" :key="index">
              <div :class="`card-row-name ${selectServer.id === item.id && 'color-blue'}`" @click="changeCard(item)">
                {{ item.name }}
              </div>
              <div class="del-btn" @click="delServer(item)">
                <i style="font-size: 18px" class="el-icon-circle-close"></i>
              </div>
            </el-card>
            <el-card class="card-row card-add" shadow="hover">
              <div class="card-row-name" @click="changeCard(null)">添加<i
                class="el-icon-circle-plus-outline"></i></div>
            </el-card>
          </div>
          <div class="car-content" v-if="selectShow">
            <el-form-item style="width: 400px" label="服务名称" prop="name">
              <el-input v-model="serveForm.name" placeholder="请输入 服务名称" size="small"></el-input>
            </el-form-item>
            <!--            <el-form-item style="width: 400px" label="机构名称" prop="companyName">-->
            <!--              <el-input v-model="serveForm.companyName" placeholder="请输入 机构名称" size="small"></el-input>-->
            <!--            </el-form-item>-->
            <el-form-item label="服务场景" prop="serveLabels">
              <tag-select v-model="serveForm.serveLabels" :prop="{ label: 'name', value: 'name' }" :data="workDataList">
              </tag-select>
            </el-form-item>
            <el-form-item label="政策指南" prop="policyIds">
              <el-cascader
                style="width: 100%"
                size="small"
                v-model="serveForm.policyIds"
                :options="listAllPolicyTree"
                :props="{ expandTrigger: 'hover', multiple: true, label: 'name', value: 'value', children: 'child'}"
                @change="handleChange"
                filterable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="重点人群" prop="talentsGroupId">
              <el-select style="width: 100%" v-model="serveForm.talentsGroupId" multiple filterable
                         placeholder="请输入 重点人群">
                <el-option
                  v-for="item in talentsList"
                  :key="item.id"
                  :label="item.groupName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="serveForm.remarks" placeholder="请输入 备注"
                        size="small"></el-input>
            </el-form-item>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <div slot="footer" style="text-align:right">
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-check"
        @click="handleSubmit"
        :loading="loading"
      >提交
      </el-button>
      <el-button size="mini" icon="el-icon-circle-close" @click=" box = false" :loading="loading">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {saveGroupServeInfo, updateDept, updateGroupServeInfo} from "@/api/tenant/serve";
import {deepClone} from "@/util/util";

const prefix = 'custom-'
const initRule = {
  groupName: [
    {
      required: true,
      whitespace: true,
      message: "请填写分组名称",
      trigger: "change",
    },
  ],
}
const initFormValue = {
  groupName: "",
  sort: 0,
}
const initServeForm = {
  companyName: '',
  name: '',
  serveLabels: [],
  policyIds: [],
  talentsGroupId: [],
  remarks: '',
}
export default {
  props: {
    treeData: {
      type: Array,
      default: [],
    },
    listAllPolicyTree: {
      type: Array,
      default: [],
    },
    data: {
      type: Array,
      default: [],
    },
    worktypeDic: {
      type: Object,
      default: {},
    },
    talentsList: {
      type: Array,
      default: [],
    }
  },
  data() {
    return {
      type: "",
      title: "",
      groupId: "",
      loading: false,
      box: false,
      form: Object.assign({}, initFormValue),
      serveForm: Object.assign({}, initServeForm),
      rules: Object.assign({}, initRule),
      activeNames: ['1', '2'],
      serveAll: [],
      selectServer: {},
      selectShow: false,
      selectLabelNameTypes: [],
      tempWorkType: [],
      tabDataSource: [],
      editData: null,
      customNum: 1,
    };
  },
  created() {
    console.log('watch', this.data)
  },
  computed: {
    workDataList() {
      let rel = deepClone(this.data)
      for (let i = 0; i < this.tempWorkType.length; i++) {
        const key = this.tempWorkType[i];
        if (key && !this.worktypeDic.hasOwnProperty(key)) {
          rel.push({name: key});
        }
      }
      return rel
    },
  },
  methods: {
    closed() {
      this.form = {
        groupName: "",
      };
      if (this.$refs.groups) {
        this.$refs.groups.resetFields();
      }
      this.loading = false;
    },
    openDialog(type, data) {
      this.type = type;
      if (this.type === "add") {
        this.title = "新建分组";
        this.form.groupName = '';
        // this.form.sort = 0;
        this.serveAll = []
        this.editData = null
        this.box = true;
      } else if (this.type === "edit") {
        this.title = "编辑分组";
        this.groupId = data.id;
        this.form.groupName = data.groupName;
        // this.form.sort = data.sort;
        this.serveAll = data.children
        this.editData = data
        this.box = true;
      }
      this.selectShow = false
      this.selectServer = {}
      this.serveForm = Object.assign({}, initServeForm)
      this.customNum = 1
    },
    async handleSubmit() {
      if (this.selectServer.id) {
        let copyForm = deepClone(this.serveForm)
        let serve = {
          ...this.selectServer,
          ...copyForm,
          policyIds: copyForm.policyIds ? copyForm.policyIds.join(',') : '',
          talentsGroupId: copyForm.talentsGroupId ? copyForm.talentsGroupId.join(',') : '',
          serveLabels: copyForm.serveLabels ? copyForm.serveLabels.map((item) => item.name).join(',') : '',
        }
        if (this.tabDataSource.find((item) => item.id === serve.id)) {
          this.tabDataSource = this.tabDataSource.map((item) => {
            if (item.id === serve.id) {
              return deepClone(serve)
            }
            return item
          })
        } else {
          this.tabDataSource = [...this.tabDataSource.filter((item) => item.id !== serve.id), deepClone(serve)]
        }
      }
      const serveAll = deepClone(this.serveAll)
      const tabDataSource = deepClone(this.tabDataSource)
      // prefix
      const customList = tabDataSource.filter((item) => /^custom-/ig.test(item.id))
      // 替换数据
      for (let i = 0; i < tabDataSource.length; i++) {
        for (let j = 0; j < serveAll.length; j++) {
          if (serveAll[j].id === tabDataSource[i].id) {
            serveAll[j] = tabDataSource[i]
            break
          }
        }
      }
      serveAll.forEach((item) => {
        if (/^custom-/ig.test(item.id)) {
          delete item.id
        }
      })
      let params, resData
      switch (true) {
        case this.type === 'add' :
          params = {
            ...this.form,
            children: serveAll
          }
          if (this.form.groupName) {
            this.loading = true;
            resData = await saveGroupServeInfo(params)
          } else {
            this.$message.error('请输入分组名称');
          }
          break
        case this.type === 'edit' :
          params = {
            ...this.editData,
            ...this.form,
            children: serveAll
          }
          if (this.form.groupName) {
            this.loading = true;
            resData = await updateGroupServeInfo(params)
          } else {
            this.$message.error('请输入分组名称');
          }
      }
      if (resData.data.code === 200) {
        this.$message.success('操作成功!');
        this.loading = false;
        this.$emit("refresh");
        this.box = false;
      } else {
        this.loading = false;
        this.$message.success('操作失败!');
      }
    },
    changeCard(data) {
      // 校验
      if (this.selectServer.id) {
        let copyForm = deepClone(this.serveForm)
        let serve = {
          ...this.selectServer,
          ...copyForm,
          policyIds: copyForm.policyIds ? copyForm.policyIds.join(',') : '',
          talentsGroupId: copyForm.talentsGroupId ? copyForm.talentsGroupId.join(',') : '',
          serveLabels: copyForm.serveLabels ? copyForm.serveLabels.map((item) => item.name).join(',') : '',
        }
        if (this.tabDataSource.find((item) => item.id === serve.id)) {
          this.tabDataSource = this.tabDataSource.map((item) => {
            if (item.id === serve.id) {
              return deepClone(serve)
            }
            return item
          })
        } else {
          this.tabDataSource = [...this.tabDataSource.filter((item) => item.id !== serve.id), deepClone(serve)]
        }
      }
      // 新增
      if (!data) {
        const fm = {
          ...Object.assign({}, initServeForm),
          name: `自定义服务名${this.customNum}`,
          id: `${prefix}${this.customNum}`
        }
        this.selectShow = true
        this.selectServer = fm
        this.serveForm = fm
        this.tempWorkType = []
        this.customNum++
        this.serveAll = [...this.serveAll, deepClone(fm)]
        this.tabDataSource.push(fm)
        return
      }

      // 回填
      let source = deepClone(data)
      if (this.tabDataSource.find((item) => item.id === data.id)) {
        source = deepClone(this.tabDataSource.filter((item) => (item.id === data.id))[0])
      } else {
        this.tabDataSource.push(data)
      }
      this.selectShow = true
      this.selectServer = source
      this.tempWorkType = source.serveLabels ? source.serveLabels.split(",") : [];
      this.serveForm.talentsGroupId = source.talentsGroupId ? source.talentsGroupId.split(',') : []
      this.serveForm.serveLabels = source.serveLabels ? source.serveLabels.split(',').map((item) => ({name: item})) : []
      const policyIds = this.treeIteration(this.listAllPolicyTree, source.policyIds.split(','))
      this.serveForm.policyIds = policyIds
      // this.serveForm.companyName = source.companyName
      this.serveForm.name = source.name
      this.serveForm.remarks = source.remarks
      this.serveForm.id = source.id
    },
    delServer(data) {
      this.serveAll = this.serveAll.filter((item) => item.id !== data.id)
      this.tabDataSource = this.tabDataSource.filter((item) => item.id !== data.id)
    },
    handleChange(policy) {
      console.log(policy)
      this.serveForm.policyIds = policy
    },
    treeIteration(tree, ids) {
      if (!(tree.length && ids.length)) return;
      let arr = []
      tree.forEach((treeItem) => {
        treeItem.child.forEach((item) => {
          if (ids.some((id) => item.value === id)) {
            arr.push([treeItem.value, item.value])
          }
        })
      })
      return arr;
    },
  },
  watch: {}
};
</script>

<style scoped>
.color-blue {
  color: blue;
}

.scroll-row {
  overflow-x: scroll;
  width: 100%;
  height: fit-content;
  display: -webkit-box;
  padding: 10px;
  margin-bottom: 10px;
}

.card-row {
  width: fit-content;
  margin-right: 10px;
  display: flex;
  align-content: center;
  justify-content: center;
  text-align: center;
  position: relative;
}

.del-btn {
  position: absolute;
  right: 0;
  top: 0;

}

.card-row-name {
  width: 100%;
  height: 100%;
}

.card-add {
  color: #e5e5e5;
}

.car-content {

}
</style>
