<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="dialogVisible"
    :title="title"
  >
    <el-row :gutter="20">
      <el-col :span="14">
        <el-form
          ref="dialogForm"
          label-position="top"
          :model="dialogForm"
          status-icon
          class="demo-form-inline"
          label-width="180"
          :rules="rules"
          style="flex: 1"
          :disabled="!editAble"
        >
          <el-form-item label="任务标题" prop="taskTitle">
            <el-input v-model="dialogForm.taskTitle" placeholder="请输入">
            </el-input>
          </el-form-item>
          <el-form-item label="任务类型" prop="taskType">
            <el-select
              v-model="dialogForm.taskType"
              placeholder="请选择任务类型"
              clearable
              filterable
              style="width: 100%;"
            >
              <el-option
                v-for="dict in dict.type.task_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>

          </el-form-item>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startDate">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.startDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择开始时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endDate">
                <el-date-picker
                  style="width: 100%"
                  v-model="dialogForm.endDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择开始时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="任务要求" prop="taskContent">
            <el-input
              v-model="dialogForm.taskContent"
              type="textarea"
              placeholder="请输入"
            >
            </el-input>
          </el-form-item>

          <el-button
            v-if="editAble"
            type="primary"
            icon="el-icon-search"
            :disabled="dialogForm.id && dialogForm.tags && dialogForm.tags.length > 0"
            @click="openTemplateDialog"
            style="margin-bottom: 5px;"
          >
            选择标签模板
          </el-button>
          <el-button
            v-if="editAble"
            type="primary"
            icon="el-icon-plus"
            @click="showTagsDialog"
            style="margin-bottom: 5px;"
            plain
          >
            选择标签
          </el-button>
          <el-table
            tooltip-effect="dark"
            :data="dialogForm.tags"
            border
            highlight-current-row>
            <el-table-column
              align="center"
              label="标签"
              show-overflow-tooltip
              min-width="160"
              prop="tagName"
            />
            <el-table-column align="center"
              label="是否拍照"
              min-width="80"
              prop="isPhoto">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isPhoto"/>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="拍摄数量"
              show-overflow-tooltip
              prop="photoNum"
            />
            <el-table-column
              v-if="editAble"
              width="80px"
              align="center"
              label="操作"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-popconfirm
                  title="删除不可恢复，确定删除吗？"
                  @confirm="handleDelete(scope.row, scope.$index)"
                >
                  <el-link type="warning" slot="reference">移除</el-link>
                </el-popconfirm>

              </template>
            </el-table-column>
          </el-table>
          <el-form-item label="" prop="file">
            <FileUpload
              v-model="dialogForm.file"
              :readonly="!editAble"
            ></FileUpload>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="10">
        <div v-loading="branchLoading">
          <div class="table-top-opretar">
            <span style="font-size: 15px;font-weight: 500;">发送到机构：</span>
            <el-button v-if="editAble" type="primary" icon="el-icon-plus" @click="toAdd"
            >新增
            </el-button>
            <el-button
              v-if="editAble"
              type="reset"
              :disabled="selectBranch.length === 0"
              icon="el-icon-delete"
              @click="toMultDelete"
            >批量删除
            </el-button>
          </div>
          <!-- 表格主体 -->
          <el-table
            ref="multipleTable"
            tooltip-effect="dark"
            :data="branchList"
            class="w100p"
            style="width: 100%;"
            height="60vh"
            @selection-change="handleSelectionChange"
            border
            header-cell-class-name="duojibiaotou"
          >
            <el-table-column type="selection" width="50"/>
            <el-table-column
              align="center"
              label="机构代码"
              show-overflow-tooltip
              min-width="90"
              prop="branchCode"
            >
            </el-table-column>
            <el-table-column
              align="center"
              label="机构名称"
              show-overflow-tooltip
              min-width="120"
              prop="branchName"
            >
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeVisible">取消</el-button>
      <el-button type="primary" v-if="editAble" v-loading="saving" @click="preSubmitForm()"
      >保存</el-button>
      <el-button v-if="editAble" type="success" v-loading="saving" @click="preSubmitForm('1')"
      >发布</el-button>
      <el-button v-if="isMe && dialogForm.status === '1'" type="warning" v-loading="saving" @click="preSubmitForm('2')"
      >办结</el-button>
    </span>
    <BranchCascaderDialog
      ref="branchCascaderDialog"
      :parentId="350000"
      @comfirm="branchChange"
    ></BranchCascaderDialog>
    <!-- 模板选择对话框 -->
    <el-dialog
      :title="'选择任务模板'"
      :visible.sync="templateDialogVisible"
      width="80%"
      append-to-body
    >
      <el-form :model="templateQuery" size="small" :inline="true" label-width="80px">
        <el-form-item label="模板名称">
          <el-input
            v-model="templateQuery.templateName"
            placeholder="请输入模板名称"
            clearable
            @keyup.enter.native="fetchTemplates"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchTemplates">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetTemplateQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="templateList"
        border
        style="width: 100%; margin-top: 16px;"
        @selection-change="handleTemplateSelection"
        :row-key="row => row.id"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="模板名称" align="center" prop="templateName"/>
        <el-table-column label="任务类型" align="center" prop="taskType" sortable='custom'>
          <template slot-scope="scope">
            <dict-tag :options="dict.type.task_type" :value="scope.row.taskType"/>
          </template>
        </el-table-column>
        <el-table-column label="任务要求" align="center" >
          <template slot-scope="scope">
            <div v-html="scope.row.taskContent"></div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTimeVo"/>
      </el-table>
      <pagination
        :total="templateTotal"
        :page.sync="templateQuery.pageNum"
        :limit.sync="templateQuery.pageSize"
        @pagination="fetchTemplates"
        style="margin-top: 16px;"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="templateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmTemplateSelection">确定</el-button>
      </div>
    </el-dialog>
    <TagsDialog ref="tagsDialog" @confirm="tagsDialogConfirm"></TagsDialog>
  </el-dialog>
</template>

<script>
import TableEditMixin from "@/mixins/table-edit-mixin";
import FileUpload from "@/components/FileUpload";
import BranchCascaderDialog from "@/components/BranchCascaderDialog";
import {addInfo, updateInfo } from "@/api/task/info";
import {
  delBranch,
  listBranch,
} from "@/api/task/branch";
import {pageListTemplate} from "@/api/task/template";
import TagsDialog from "./TagsDialog";
import { delTag, listTag } from "@/api/task/tag";

export default {
  components: {
    FileUpload,
    BranchCascaderDialog,
    TagsDialog,
  },
  mixins: [TableEditMixin],
  dicts: ['task_type', 'sys_yes_no'], // 添加字典声明
  pageInfo: {
    defaultForm: {
      status: "0", // 0未发布，1已发布 2已完成/办结
      startDate: null,
      endDate: null,
    },
    title: "任务",
    updateApi: updateInfo,
    addApi: addInfo,
  },
  data() {
    return {
      rules: {
        taskTitle: [
          {required: true, message: "请输入任务标题", trigger: "blur"},
          {min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur"}
        ],
        taskType: [
          {required: true, message: "请选择任务类型", trigger: "change"}
        ],
        startDate: [
          {required: true, message: "请输入开始时间", trigger: "change"}
        ],
        endDate: [
          {required: true, message: "请输入结束时间", trigger: "change"}
        ],
        taskContent: [
          {required: true, message: "请输入任务要求", trigger: "blur"},
        ]
      },
      file: [],
      branchList: [],
      selectBranch: [],
      branchLoading: false,
      isSubmit: '',
      templateDialogVisible: false,
      templateList: [],
      templateTotal: 0,
      templateQuery: {
        templateName: '',
        pageNum: 1,
        pageSize: 10
      },
      selectedTemplate: null
    };
  },
  computed: {
    editAble() {
      return !this.dialogForm.id || (this.dialogForm.status === '0' && this.isMe);
    },
    isMe() {
      return !this.dialogForm.publisher || this.dialogForm.publisher == this.$store.getters?.userInfo?.userId;
    }
  },
  methods: {
    open(data = {}) {
      this.title = `${data.id ? "编辑" : "新增"}${
        this.$options.pageInfo.title
      }`;
      this.dialogVisible = true;
      this.dialogForm = {...this.$options.pageInfo.defaultForm, ...data};
      if (this.dialogForm.id && this.dialogForm.userId !== this.$store.getters?.userInfo?.userId) {
        this.title = `查看${
          this.$options.pageInfo.title
        }`;
      }
      if (!data.id) {
        this.dialogForm.publisher = this.$store.getters?.userInfo?.userId;
      }
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate();
      });
      this.branchList = [];
      this.selectBranch = [];
      this.getBranchList();

      if (data.id) {
        listTag({taskId: this.dialogForm.id}).then(res => {
          this.$set(this.dialogForm, "tags", res.data || []);
        }).catch(e => {

        });
      }
    },
    toAdd() {
      this.$refs.branchCascaderDialog.open();
    },
    toMultDelete() {
      const ids = this.selectBranch.filter((v) => !!v.id).map((v) => v.id);
      this.$confirm(`确定删除选中的机构?`, "批量删除提示", {
        type: "warning",
      }).then((e) => {
        if (ids.length === 0) {
          this.branchList = this.branchList.filter(
            (v) => !this.selectBranch.includes(v)
          );
          return;
        }
        this.branchLoading = true;
        delBranch(ids)
          .then((res) => {
            this.branchList = this.branchList.filter(
              (v) => !this.selectBranch.includes(v)
            );
            this.branchLoading = false;
          })
          .catch((e) => {
            this.branchLoading = false;
          });
      });
    },
    handleSelectionChange(val) {
      this.selectBranch = val;
    },
    getBranchList() {
      if (!this.dialogForm.id) return;
      this.branchLoading = true;
      listBranch({
        taskId: this.dialogForm.id,
      })
        .then((res) => {
          this.branchList = res.data || [];
          this.branchLoading = false;
        })
        .catch((e) => {
          this.branchLoading = false;
        });
    },
    branchChange(val) {
      val.forEach((item) => {
        if (this.branchList.some((v) => v.branchCode === item.deptId + "")) {
          return;
        }
        this.branchList.push({
          branchCode: item.deptId + "",
          branchName: item.deptName,
          taskStatus: "0", // 0未发布， 1已发布
        });
      });
    },
    preSubmitForm(type) {
      if (this.branchList.length === 0) {
        this.$message.error("请选择发送到机构");
        return;
      }
      this.isSubmit = type;
      if (type === '1' || type === '2') {
        this.$confirm(`确定${type === '1' ? '发布' : '办结'}任务?`, "温馨提示", {
          type: "warning"
        }).then(res => {
          this.submitForm();
        });
        return;
      }
      this.submitForm();
    },
    combinDialogForm() {
      if (this.isSubmit === '1' || this.isSubmit === '2') {
        return {
          ...this.dialogForm,
          branchList: this.branchList.map(val => {
            const newVal = {...val};
            if (!newVal.taskStatus || newVal.taskStatus === '0') {
              newVal.taskStatus = this.isSubmit;
            } else if (newVal.taskStatus === '1' && this.isSubmit === '2') {
              newVal.taskStatus = this.isSubmit;
            }
            return newVal;
          }),
          status: this.isSubmit,
        };
      }
      return {
        ...this.dialogForm,
        branchList: this.branchList,
      };
    },
    // 模板选择相关方法
    openTemplateDialog() {
      this.templateDialogVisible = true;
      this.resetTemplateQuery();
    },
    async fetchTemplates() {
      try {
        const response = await pageListTemplate(this.templateQuery);
        this.templateList = response.rows;
        this.templateTotal = response.total;
      } catch (error) {
        this.$message.error("获取模板列表失败");
      }
    },
    resetTemplateQuery() {
      this.templateQuery = {
        templateName: '',
        pageNum: 1,
        pageSize: 10
      };
      this.fetchTemplates();
    },
    handleTemplateSelection(selection) {
      this.selectedTemplate = selection.length > 0 ? selection[0] : null;
    },
    confirmTemplateSelection() {
      if (!this.selectedTemplate) {
        return this.$message.warning("请选择一个任务模板");
      }
      this.dialogForm.taskType = this.selectedTemplate.taskType;
      // 移除 HTML 标签
      // 空值处理
      const taskContent = this.selectedTemplate.taskContent || '';
      const textContent = taskContent.replace(/<[^>]*>/g, '');
      this.dialogForm.taskContent = textContent;
      this.templateDialogVisible = false;
      this.dialogForm.tags = this.selectedTemplate.tags.map(val => {
        return {
          ...val,
          _id: val.id,
          id: null,
        };
      });
    },
    showTagsDialog() {
      this.$refs.tagsDialog.open();
    },
    tagsDialogConfirm(data) {
      if (!this.dialogForm.tags) {
        this.$set(this.dialogForm, 'tags', []);
      }
      const list = data.filter(val => !this.dialogForm.tags.some(i => i._id === val.id)).map(val => {
        return {
          ...val,
          _id: val.id,
          id: null,
        };
      });
      this.dialogForm.tags.push(...list);
    },
    handleDelete(row, index) {
      if (row.id) {
        delTag(row.id).then(() => {
          this.dialogForm.tags.splice(index, 1);
        });
      } else {
        this.dialogForm.tags.splice(index, 1);
      }
    }
  },
};
</script>

<style>
</style>
