<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模版名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模版名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-tree-select
          v-model="queryParams.deptId"
          :data="deptOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }"
          value-key="id"
          placeholder="请选择归属部门"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="模板分类" prop="modelType">
        <el-select
          v-model="queryParams.modelType"
          placeholder="模板分类"
          clearable
        >
          <el-option
            v-for="dict in t_state_model_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否下发" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="是否下发"
          clearable
        >
          <el-option
            v-for="dict in t_state_model_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:stateModel:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:stateModel:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:stateModel:remove']"
        >删除
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['business:stateModel:export']"-->
<!--        >导出-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stateModelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模板序号" align="center" prop="modelId" :show-overflow-tooltip="true"/>
      <el-table-column label="模版名称" align="center" prop="modelName"/>
      <el-table-column label="是否下发" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="t_state_model_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="模板类型" align="center" prop="modelType">
        <template #default="scope">
          <dict-tag :options="t_state_model_type" :value="scope.row.modelType"/>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)"
                     v-hasPermi="['business:stateModel:list']">查看
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['business:stateModel:edit']" v-if="Number(scope.row.status) === 0">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['business:stateModel:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改调查问卷模板对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="stateModelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模版名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模版名称"/>
        </el-form-item>
        <el-form-item label="模板分类" prop="modelType">
          <el-radio-group v-model="form.modelType" @change="changeCheckValue">
            <el-radio
              :label="dict.value"
              v-for="dict in t_state_model_type"
              :key="dict.value">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select
            v-model="form.deptId"
            :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="请选择归属部门"
            check-strictly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="stateFormAllSubmit()">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改调查问卷模板对话框 -->
    <el-dialog title="设计题目" v-model="openForm" fullscreen append-to-body :close-on-click-modal="false">
      <StateFormAll v-model="form.modelForms" :checkValue="Number(checkValue)" @onSubmit="submitForm()"></StateFormAll>
    </el-dialog>
    <!-- 查看题目 -->
    <el-dialog title="查看题目" v-model="openFormView" append-to-body>
      <StateFormView v-model="formView"></StateFormView>
    </el-dialog>
  </div>
</template>

<script setup name="StateModel">
import {listStateModel, getStateModel, delStateModel, addStateModel, updateStateModel} from "@/api/business/stateModel";
import {deptTreeSelect} from "@/api/system/user";
import {getCurrentInstance, ref} from "vue";
import StateFormAll from "@/components/StateFormAll";
import StateFormView from "@/components/StateFormView";

const {proxy} = getCurrentInstance();

const stateModelList = ref([]);
const open = ref(false);
const openForm = ref(false);
const openFormView = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const deptOptions = ref(undefined);
let checkValue = ref(null);
const {t_state_model_type, t_state_model_status} = proxy.useDict("t_state_model_type","t_state_model_status");
const formView = ref([])

const data = reactive({
  form: {
    modelForms: [],
    status: 0
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelName: null,
    modelType: null,
    deptId: null,
    createTime: null,
    status: null
  },
  rules: {
    modelName: [
      {required: true, message: "模板名称不能为空", trigger: "blur"}
    ],
    modelType: [
      {required: true, message: "模板类型不能为空", trigger: "blur"}
    ],
    deptId: [
      {required: true, message: "部门不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询调查问卷模板列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' !== daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listStateModel(queryParams.value).then(response => {
    stateModelList.value = response.rows;
    total.value = Number(response.total);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    modelId: null,
    modelName: null,
    modelType: null,
    deptId: null,
    modelForms: [],
    status: 0
  };
  proxy.resetForm("stateModelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.modelId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加调查问卷模板";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _modelId = row.modelId || ids.value
  if (Number(row.status) !== 0 ){
    proxy.$modal.msgError("禁止修改！");
    return;
  }
  getStateModel(_modelId).then(response => {
    form.value = response.data;
    open.value = true;
    checkValue.value = form.value.modelType
    title.value = "修改调查问卷模板";
  });
}

/** 提交按钮 */
function submitForm() {
  if (form.value.modelId != null) {
    updateStateModel(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      openForm.value = false;
      getList();
    });
  } else {
    addStateModel(form.value).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      openForm.value = false;
      getList();
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _modelIds = row.modelId || ids.value;
  proxy.$modal.confirm('是否确认删除调查问卷模板编号为"' + _modelIds + '"的数据项？').then(function () {
    return delStateModel(_modelIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/stateModel/export', {
    ...queryParams.value
  }, `stateModel_${new Date().getTime()}.xlsx`)
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
}

//创建模板 并校验参数
function stateFormAllSubmit() {
  proxy.$refs["stateModelRef"].validate(valid => {
    if (valid) {
      console.log(valid)
      openForm.value = true
      open.value = false
    }
  });
}

//判断选择的的类型是否需要验证答案
function changeCheckValue(e) {
  checkValue.value = e
}

//查看题目
function handleView(row) {
  formView.value.slice(0, formView.value.length)
  const _modelId = row.modelId || ids.value
  getStateModel(_modelId).then(response => {
    formView.value = response.data.modelForms;
    openFormView.value = true
  });

}

getDeptTree();
getList();
</script>
