<template>
  <div class="app-container">
    <div class="btn_grooup" v-if="bo.winningState == 0 && '0-1'.includes(boAuthority.post)">
      <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button>
    </div>
    <el-table size="mini" v-loading="loading" :data="taskList" >
      <el-table-column label="序号" type="index" width="50" align="center" fixed/>
      <el-table-column width="200" show-overflow-tooltip label="任务名称" align="center" prop="name" />
      <el-table-column width="500" show-overflow-tooltip label="任务内容" align="center" prop="content" />
      <el-table-column label="任务状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mk_bo_taskstate"
            :value="scope.row.state"
          />
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="staffName" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center" prop="deadlineTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadlineTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createByName" />
      <el-table-column
        width="250"
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
        v-if="bo.winningState == 0 ? true : false"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleBrowse(scope.row)"
            >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-top"
            @click="submitTask(scope.row)"
            v-if="scope.row.state == 0 && '0-1'.includes(boAuthority.post) && scope.row.createBy == $store.state.user.name"
            >提交</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.state == 0 && '0-1'.includes(boAuthority.post) && scope.row.createBy == $store.state.user.name"
            >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.state == 0 && '0-1'.includes(boAuthority.post) && scope.row.createBy == $store.state.user.name"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改任务对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        size="mini"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        :disabled="operatingState == 'Browse'"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="商机名称" prop="boName">
              <el-input
                v-model="form.boName"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商机阶段" prop="boStage">
              <el-input v-model="form.boStage" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户" prop="customerName">
              <el-input
                v-model="form.customerName"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="任务编码" prop="code">
              <el-input
                v-model="form.code"
                placeholder="系统自动生成编码"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务状态" prop="state">
              <el-select v-model="form.state" placeholder="请输入任务状态">
                <el-option
                  v-for="dict in dict.type.mk_bo_taskstate"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                clearable
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                :picker-options="editStartOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="截止时间" prop="deadlineTime">
              <el-date-picker
                clearable
                v-model="form.deadlineTime"
                type="date"
                value-format="yyyy-MM-dd"
                :picker-options="editStopOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务类型" prop="type">
              <el-select v-model="form.type" placeholder="">
                <el-option
                  v-for="dict in dict.type.mk_bo_tasktype"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人" prop="linkmanName">
              <dr-popover-select
                v-model="form.linkmanName"
                title="联系人选择"
                type="LINKMAN_PARAM"
                :dataMapping="{
                  linkman: 'id',
                  linkmanName: 'name',
                }"
                :source.sync="form"
                :queryParams="additionalCondition"
              >
              </dr-popover-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="staffName">
              <dr-popover-select
                v-model="form.staffName"
                title="联系人选择"
                type="CONTACTS_PARAM"
                :dataMapping="{
                  staff: 'code',
                  staffName: 'name',
                }"
                :source.sync="form"
              >
              </dr-popover-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务内容" prop="content">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入任务内容"
            autosize
            v-model="form.content"
          >
          </el-input>
        </el-form-item>
        <el-divider content-position="left">其它信息</el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="创建人">
              <el-input
                v-model="form.createByName"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">
              <el-input
                v-model="form.createTime"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="修改人">
              <el-input
                v-model="form.updateByName"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="修改时间">
              <el-input
                v-model="form.updateTime"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <BehaviorList
          :key="timer"
          :source="'TASK'"
          :task="form"
          v-if="operatingState == 'Browse'"
        />
        
      <div slot="footer">
        <el-button
          size="mini"
          type="primary"
          @click="submitForm"
          v-if="operatingState != 'Browse'"
          :disabled="submitButtonEditStatus"
          >确 定</el-button
        >
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTask,
  delTask,
  addTask,
  updateTask,
  submit
} from "@/api/business/spd/bo/task";
import {listTask} from "@/api/business/spd/bo/basic";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import BehaviorList from "./behaviorList.vue";

export default {
  name: "TaskList",
  props: ["bo", "boAuthority"],
  dicts: ["mk_bo_taskstate", "mk_bo_tasktype", "mk_bo_stage"],
  components: {
    BehaviorList,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bo: null,
        boStage: null,
        code: null,
        name: null,
        type: null,
        state: null,
        customer: null,
        customerName: null,
        linkman: null,
        linkmanName: null,
        salesOrg: null,
        salesOrgName: null,
        dept: null,
        deptName: null,
        staff: null,
        staffName: null,
        startTime: null,
        deadlineTime: null,
        content: null,
        tenantId: null,
        revision: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerName: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "任务名称不能为空", trigger: "blur" },
        ],
        state: [
          { required: true, message: "任务状态不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "任务类型不能为空", trigger: "blur" },
        ],
        linkmanName: [
          { required: true, message: "联系人不能为空", trigger: "blur" },
        ],
        staffName: [
          { required: true, message: "负责人不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: ["blur", "change"] },
        ],
        deadlineTime: [
          { required: true, message: "截止时间不能为空", trigger: ["blur", "change"] },
        ],
        content: [
          { required: true, message: "任务内容不能为空", trigger: "blur" },
        ],
      },
      //重新加载子组件参数
      timer: "",
      //当前操作状态
      operatingState: "",
      editStartOptions: {
        disabledDate: time => {
          if (!this.form.deadlineTime) {
            return time.getTime() < new Date(1970 - 1 - 1).getTime();   //禁止选择1970年以前的日期
          } else {
            return time.getTime() > new Date(this.form.deadlineTime);
          }
        }
      },
      editStopOptions: {
        disabledDate: time => {
          return (
            time.getTime() < new Date(this.form.startTime) ||
            time.getTime() < new Date(1970 - 1 - 1).getTime()    //禁止选择1970年以前的日期
          );
        }
      },
      //确定按钮是否可点
      submitButtonEditStatus:false,
      //提交任务
      submitTask(row){
        submit(row.id).then((response) => {
          if(response.code == 200){
            this.$modal.msgSuccess("提交成功");
            this.getList();
          }
        });
      },
    };
  },
  created() {
    this.queryParams.id = this.bo.id;
    let params = {"post":this.boAuthority.post};
    this.queryParams.params = params;
    this.getList();
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then((response) => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bo: null,
        boStage: null,
        code: null,
        name: null,
        type: null,
        state: null,
        customer: null,
        customerName: null,
        linkman: null,
        linkmanName: null,
        salesOrg: null,
        salesOrgName: null,
        dept: null,
        deptName: null,
        staff: null,
        staffName: null,
        startTime: null,
        deadlineTime: null,
        content: null,
        tenantId: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.operatingState = "Insert";
      this.reset();
      this.form.bo = this.bo.id;
      this.form.boName = this.bo.boName;
      this.form.boStage = this.bo.boStage;
      this.form.customer = this.bo.customer;
      this.form.customerName = this.bo.customerName;
      this.form.startTime = new Date();
      this.form.state = "0";
      this.form.dept = this.$store.state.user.adminDept;
      this.form.deptName = this.$store.state.user.adminDeptName;
      this.form.salesOrg = this.$store.state.user.orgId;
      this.form.salesOrgName = this.$store.state.user.orgName;
      this.form.createBy = this.$store.state.user.name;
      this.form.createByName = this.$store.state.user.nickName;
      this.form.createTime = new Date().Format("yyyy-MM-dd HH:mm:ss");
      this.open = true;
      this.title = "添加任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.operatingState = "Update";
      this.reset();
      const id = row.id;
      getTask(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改任务";
        this.timer = new Date().getTime();
      });
    },
    /** 查看按钮操作 */
    handleBrowse(row) {
      this.reset();
      const id = row.id;
      getTask(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.operatingState = "Browse";
        this.title = "基础信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.submitButtonEditStatus = true;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.submitButtonEditStatus = false;
            });
          } else {
            addTask(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.submitButtonEditStatus = false;
            });
          }
        }else{
          this.submitButtonEditStatus = false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除任务编号为"' + row.code + '"的数据项？')
        .then(function () {
          return delTask(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //联系人弹窗附加查询条件
    additionalCondition(){
      return {
        parame:{
          customer: this.form.customer
        }
      }
    },
    // 触发员工参照列表
    refereStaff() {
      this.$refs.staffSelect.init();
    },
    //员工参照列表选择后
    staffSelectionsToInput(selections) {
      this.form.staff = selections[0].userName;
      this.form.staffName = selections[0].nickName;
      this.form.dept = selections[0].deptId;
      this.form.deptName = selections[0].deptName;
      this.form.salesOrg = selections[0].orgId;
      this.form.salesOrgName = selections[0].orgName;
    },
  },
};
</script>

<style lang="scss" scoped>
.btn_grooup {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
