<!--
 * @Author: tengmingxue 1473375109@qq.com
 * @Date: 2023-08-29 16:44:32
 * @LastEditors: tengmingxue 1473375109@qq.com
 * @LastEditTime: 2023-09-21 17:21:11
 * @FilePath: \xld-gis-admin\src\views\dataAdmin\dataAdmin\configProcess\addStepForm.vue
 * @Description: 流程步骤配置表单
-->
<template>
  <a-form ref="formRef" :model="formState" :rules="formState.xh === 1 ? rules1 : rules" class="step-form">
    <a-form-item ref="xh" label="步骤序号" name="xh" :labelCol="{ span: 4 }" :wrapper-col="{ span: 18 }">
      <a-input-number :min="1" :max="10" v-model:value="formState.xh" :disabled="true" style="width: 50px; float: left" />
      <div class="btn-group" v-show="optType !== 3">
        <span class="addBtn btn" @click="stepEdit(1)">+</span>
        <span class="redBtn btn" @click="stepEdit(-1)">-</span>
      </div>
    </a-form-item>
    <a-form-item ref="name" label="步骤名称" name="name" :labelCol="{ span: 4 }" :wrapper-col="{ span: 12 }">
      <a-input v-model:value="formState.name" @change="stepInfoChange" :disabled="formState.xh === 1 || optType === 3" />
    </a-form-item>
    <a-form-item v-if="formState.xh !== 1" ref="model" label="处理模式" name="model" :labelCol="{ span: 4 }"
      :wrapper-col="{ span: 12 }">
      <a-radio-group v-model:value="formState.model" @change="stepInfoChange" :disabled="optType === 3">
        <a-radio value="1">逐级</a-radio>
        <a-radio value="2">并行</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="formState.xh !== 1" ref="dept" label="处理部门" name="dept" :labelCol="{ span: 4 }"
      :wrapper-col="{ span: 12 }">
      <a-tree-select show-search style="width: 100%" :replaceFields="replaceFields" :tree-data="treeData"
        v-model:value="formState.dept" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择处理部门"
        allow-clear multiple tree-default-expand-all @change="treeSelectChange" :disabled="optType === 3">
        <template #title="{ key, value }">
          <span style="color: #08c" v-if="key === '0-0-1'">Child Node1 {{ value }}</span>
        </template>
      </a-tree-select>
    </a-form-item>
    <a-form-item v-if="formState.xh !== 1" ref="user" label="处理人员" name="user" :labelCol="{ span: 4 }"
      :wrapper-col="{ span: 12 }">
      <a-select v-model:value="formState.user" placeholder="请选择处理人员" mode="multiple" style="width: 100%"
        :disabled="optType === 3">
        <template v-for="user in handlers" :key="user.userid">
          <a-select-option :value="user['userId']">{{ user['userName'] }}</a-select-option>
        </template>
      </a-select>
    </a-form-item>
    <a-table v-if="formState.user.length > 0" bordered :data-source="formState.userList" :columns="columns"
      :pagination="false" style="height: 100%">
      <template #operation="{ record }">
        <template v-if="optType !== 3">
          <a v-if="record.xh !== 1" style="color: #2d74e7; margin: 10px" @click="moveClick(-1, record)">上移</a>
          <a v-if="record.xh < formState.userList.length" style="color: #2d74e7; margin: 10px"
            @click="moveClick(1, record)">下移</a>
        </template>
        <template v-else>
          <a v-if="record.xh !== 1" style="color: #9c9d9e; margin: 10px">上移</a>
          <a v-if="record.xh < formState.userList.length" style="color: #9c9d9e; margin: 10px">下移</a>
        </template>
      </template>
    </a-table>
  </a-form>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, onMounted, watch, UnwrapRef, toRaw } from 'vue';
import { cloneDeep } from 'lodash-es';
import { DeleteOutlined } from '@ant-design/icons-vue';
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import { structureList } from '/@/api/sys/position';
import { queryPersonByDepId } from '/@/api/sys/user';

const props = {
  currStep: { type: Object, require: true },
  optType: { type: Number, require: true },
};
interface FormState {
  xh: number;
  name: string;
  model: string;
  dept: string[];
  user: string[];
  userList: object[];
}
export default defineComponent({
  name: 'AddStepForm',
  components: { DeleteOutlined },
  props,
  setup(props, { emit }) {
    let currStep = ref(props.currStep);
    const optType = ref(props.optType);
    const formRef = ref();
    const columns = [
      {
        title: '处理顺序',
        dataIndex: 'xh',
        width: '30%',
        align: 'center',
      },
      {
        title: '人员',
        dataIndex: 'userName',
        width: '40%',
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: '30%',
        align: 'center',
        slots: { customRender: 'operation' },
      },
    ];

    const replaceFields = { children: 'children', title: 'departName', key: 'id', value: 'value' };

    const treeData = ref([]);

    const handlers = ref([]);

    let formState = ref({
      xh: 1,
      name: '',
      model: '1',
      dept: [],
      user: [],
      userList: [],
    });
    const rules = {
      name: [{ required: true, message: '请填写步骤名称', trigger: 'blur' }],
      model: [{ required: true, message: '请选择处理模式', trigger: 'change' }],
      dept: [{ required: true, message: '请选择处理部门', trigger: 'change', type: 'array' }],
      user: [{ required: true, message: '请选择处理人员', trigger: 'change', type: 'array' }],
    };
    const rules1 = {
      name: [{ required: true, message: '请填写步骤名称', trigger: 'blur' }],
    };

    watch(
      () => props.currStep,
      (obj) => {
        currStep.value = obj;
        formState.value.xh = currStep.value?.xh ? currStep.value?.xh : 1;
        formState.value.name = currStep.value?.name ? currStep.value?.name : '';
        formState.value.model = currStep.value?.model ? currStep.value?.model : '1';
        formState.value.dept = currStep.value?.dept ? currStep.value?.dept : [];
        treeSelectChange(formState.value.dept, null, null);
        formState.value.user = currStep.value?.user ? currStep.value?.user : [];
        //formState.value.userList =  currStep.value?.userList ? currStep.value?.userList : [];
        //changeUserId(formState.value.user)
      }
    );

    watch(
      () => props.optType,
      (i) => {
        optType.value = i;
      }
    );

    watch(
      () => formState.value.user,
      (list) => {
        changeUserId(list);
      }
    );
    /**
     * 用户改变
     */
    const changeUserId = async (ids) => {
      formState.value.userList = [];
      if (!ids || ids.length < 1) return;
      if (handlers.value.length === 0) await queryUsers(formState.value.dept);
      ids.map((item, index) => {
        const obj = handlers.value.find((user) => user['userId'] === item) as any;
        if (obj) {
          obj['xh'] = index + 1;
          formState.value.userList.push(obj);
        }
      });
      stepInfoChange();
    };

    /**
     * 信息内容改变
     */
    const stepInfoChange = () => {
      emit('editStep', formState.value);
    };

    const stepEdit = (flag) => {
      if (flag === 1) {
        formRef.value
          .validate()
          .then(() => {
            console.log('values', formState.value, toRaw(formState.value));
            //校验通过
            formState.value.xh = formState.value.xh + 1;
            formState.value.name = '';
            formState.value.model = '1';
            formState.value.dept = [];
            formState.value.user = [];
            const stepInfo = cloneDeep({
              xh: formState.value.xh,
              name: '',
              model: '',
              dept: [],
              user: [],
            });
            emit('editStep', stepInfo);
          })
          .catch((error: ValidateErrorEntity<FormState>) => {
            console.log('校验失败', error);
          });
      }
      if (flag === -1) {
        //删除当前数据
        emit('reduceStep', cloneDeep(formState.value));
      }
    };

    /**
     * 校验数据完整性
     */
    const validateForm = () => {
      return new Promise((resolve) => {
        formRef.value
          .validate()
          .then(() => {
            resolve(true);
          })
          .catch((error: ValidateErrorEntity<FormState>) => {
            console.log('校验失败', error);
            resolve(false);
          });
      });
    };

    /**
     * 审核顺序改变
     */
    const moveClick = (flag, row) => {
      //1、修改顺序
      const obj = formState.value.userList.find((item) => item['xh'] === row.xh);
      const index = formState.value.userList.indexOf(obj);
      if (index < 0) return;
      const temp = cloneDeep(formState.value.userList[index]);
      const increment = flag;
      formState.value.userList[index] = cloneDeep(formState.value.userList[index + increment]);
      formState.value.userList[index + increment] = cloneDeep(temp);
      //2、重新生成序号
      formState.value.userList.forEach((item, index) => {
        item['xh'] = index + 1;
      });
    };

    const queryDept = async () => {
      const res = (await structureList()) as any;
      if (res && res.length > 0) {
        treeData.value = dealData(res);
      }
    };
    /**
     * 查询人员信息
     */
    const queryUsers = async (nodeIds) => {
      const formData = new FormData();
      formData.append('depId', nodeIds.toString());
      const res = (await queryPersonByDepId(formData)) as any;
      if (res && res.resp_code === 0) {
        //过滤userId不存在的
        handlers.value = res?.datas ? res?.datas : [];
        handlers.value = handlers.value.filter((user) => user['userId'] != null);
      }
    };

    const treeSelectChange = async (nodeIds, nodeNames, nodes) => {
      console.log('选择部门', nodeIds, nodeNames, nodes);
      if (nodeIds.length > 0) queryUsers(nodeIds);
      else {
        handlers.value = [];
      }
      stepInfoChange();
    };

    /**
     * 处理显示的数据只有叶子节点可以被选中
     */
    const dealData = (param) => {
      return param.map((item) => ({
        ...item,
        disabled: !!item.children,
        children: item.children ? dealData(item.children) : [],
      }));
    };

    /**
     * 清理数据
     */
    const clearFormData = () => {
      formState.value = {
        xh: 1,
        name: '',
        model: '1',
        dept: [],
        user: [],
        userList: [],
      };
      formRef.value.resetFields();
    };

    onMounted(async () => {
      queryDept();
    });

    return {
      formRef,
      treeData,
      replaceFields,
      formState,
      rules,
      rules1,
      handlers,
      columns,
      stepEdit,
      currStep,
      optType,
      validateForm,
      stepInfoChange,
      moveClick,
      queryDept,
      queryUsers,
      changeUserId,
      dealData,
      treeSelectChange,
      clearFormData,
    };
  },
});
</script>
<style scoped lang="less">
.step-form {
  height: 100%;
  overflow: auto;

  .btn-group {
    float: left;
    height: 30px;
    width: 80px;
    display: flex;
    align-items: center;

    .btn {
      float: left;
      height: 20px;
      line-height: 15px;
      width: 20px;
      margin-left: 10px;
      color: #fff;
      font-size: 20px;
      font-weight: bold;
      display: flex;
      justify-content: center;
      border-radius: 50%;
      text-align: center;
      cursor: pointer;
    }

    .addBtn {
      background: #0671dd;
    }

    .redBtn {
      background: #f84242;
    }
  }
}
</style>
    