<template>
  <div class="app-container order-index">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
       class="mini-form"
    >
      <el-form-item label="任务创建时间:" prop="platformName">
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="任务状态:" prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          filterable
          multiple
          style="width: 155px;"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="(dict, index) in taskStatusList"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务分类:" prop="taskType">
        <el-select
          v-model="queryParams.taskType"
          filterable
          multiple
          style="width: 155px;"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="(dict, index) in taskTypeList"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus" 
        size="mini" @click="handleAdd" v-hasPermi="['system:shop:addplatform']"
          >新增重跑台账任务</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="proTable"
      :height="tableHeight"
      border
      v-loading="loading"
      row-key="id"
      :data="postList"
    >
      <!-- <el-table-column type="selection" min-width="55" align="center" /> -->
      <el-table-column label="台账程序版本" min-width="120" align="left" prop="version" />
      <el-table-column label="重跑台账日期范围" min-width="180" align="center" prop="shopName">
        <template template slot-scope="scope">
          <span>{{ scope.row.startDate }}~{{ scope.row.endDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" min-width="90" align="center" prop="taskStatusName" />
      <el-table-column label="任务分类" min-width="100" align="center" prop="taskTypeName" />
      <el-table-column label="原因说明" min-width="150" align="center" prop="remark" />
      <el-table-column label="创建人" min-width="100" align="center" prop="createdByName" />
      <el-table-column label="创建时间" min-width="110" align="center" prop="createdTime" />
      <el-table-column label="任务运行时间" min-width="180" align="center" prop="sort">
        <template template slot-scope="scope">
          <span v-if="scope.row.taskStartTime">{{ scope.row.taskStartTime }}~{{ scope.row.taskEndTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="130"
        align="center"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" 
          v-if="scope.row.taskStatusName=='待审批'||scope.row.taskStatusName=='审批打回'" 
          @click="showChart(scope.row)" 
            >编辑</el-button
          >
          <el-button size="mini" type="text" @click="showLog(scope.row)"
            >日志</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog
      :title="title"
      top="50px"
      :visible.sync="open"
      width="500px"
      append-to-body
      center
    >
      <el-form 
      ref="spuRef" 
      class="mini-form" 
      size="mini"
       :model="form" label-width="120px">
        <el-form-item
          label="台账程序版本:"
          :rules="[{ required: true, message: '请选择台账程序版本', trigger: 'change' }]"
          prop="version"
        >
          <el-select
            v-model="form.version"
            placeholder="请选择台账程序版本"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="(dict, index) in versionLists"
              :key="index"
              :label="dict.versionName"
              :value="dict.versionCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="重跑台账日期范围:"
          :rules="[{ required: true, message: '请选择重跑台账日期范围', trigger: 'change' }]"
          prop="dateRange"
        >
        <el-date-picker
          v-model="form.dateRange"
          style="width: 100%;"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="重跑分类:"
          prop="taskType"
        >
          <el-select
            v-model="form.taskType"
            placeholder="请选择台账程序版本"
            clearable
            disabled
            style="width: 100%;"
          >
            <el-option
              v-for="(dict, index) in taskTypeList"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="重跑原因说明:"
          :rules="[{ required: true, message: '请填写重跑原因说明', trigger: 'change' }]"
          prop="remark"
        >
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="100字以内"
            maxLength="100"
            :rows="4"
            clearable
          />
        </el-form-item>
        <el-alert type="warning" :closable="false" show-icon title='手工重跑台账任务提交后将发起飞书审批流程，飞书审批通过后触发台账重跑任务'/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitDataScope">确 定</el-button>
        <el-button size="mini" @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="日志"
      :visible.sync="logVisible"
      width="700px"
      append-to-body
      center
    >
      <el-table
        ref="logTable"
        border
        :data="operationLogList"
      >
        <!-- <el-table-column type="selection" min-width="55" align="center" /> -->
          <el-table-column
            label="操作步骤"
            min-width="140"
            align="left"
            prop="logType"
          >
          </el-table-column>
          <el-table-column label="操作备注" min-width="140" align="left" prop="logMsg">
            <template slot-scope="scope">
              <span v-html="scope.row.logMsg"></span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作人"
            min-width="100"
            align="left"
            prop="createdByName"
          />
          <el-table-column
            label="操作时间"
            min-width="140"
            align="left"
            prop="createdTime"
          />
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { 
  orderFlowQueryPage, 
  versionList, 
  orderFlowAdd, 
  orderFlowUpdate,
  orderFlowLog
} from '@/api/orderFlow/index';
import { getToday2, getValueDaysAgo2 } from "@/utils/index";

export default {
  name: "orderFlow",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      taskStatusList: [
        { label: "待审批", value: "0" },
        { label: "审批打回", value: "1" },
        { label: "审批通过", value: "2" },
        { label: "运行中", value: "3" },
        { label: "运行结束", value: "4" },
        { label: "运行失败", value: "5" },
      ],
      taskTypeList: [
        { label: "手工重跑", value: "MANUAL_RE_RUN" },
        { label: "财务调整台账", value: "FINANCIAL_ADJUST" },
        { label: "系统定时程序", value: "CRONJOB" },
        { label: "导入月度仓储账单", value: "WAREHOUSE_BILL_UPDATE" },
        { label: "导入拼多多补贴", value: "OPERATE_BILL_UPDATE" },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      logVisible: false,
      operationLogList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/spu/import",
      },
      // 查询参数
      queryParams: {
        "endDate": "",
        "pageIndex": 1,
        "pageSize": 10,
        "startDate": "",
        "taskStatus": [],
        "taskType": [],
        dateRange: []
      },
      // 表单参数
      form: { 
        "endDate": "",
        "remark": "",
        "startDate": "",
        "taskType": "MANUAL_RE_RUN",
        "version": "",
        dateRange: []
      },
      tableHeight: "auto",
      versionLists: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.queryParams.dateRange = [getValueDaysAgo2(7), getToday2()];
    this.getList();
    this.getVersionList();
  },
  mounted() {},
  methods: {
    getVersionList() {
      versionList({}).then(res=>{
        this.versionLists = res.data.list;
      })
    },
    platformChange(value){
      const data = this.platformList.find(item=> item.platformNo == value);
      this.form2.platformName = data ? data.platformName : '';
    },
    deptChange(value){
      const data = this.deptList.find(item=> item.deptCode == value);
      this.form2.departmentName = data ? data.deptName : '';
    },
    shopChange(item, value, keys,key, list){
      const data = list.find(items=> items[keys] == value);
      item[key] = data ? data[key] : '';
    },
    shopChange2(item, value){
      const data = this.erpShopList.find(items=> items.shopCode == value);
      item.erpShopName = data ? data.shopName : '';
    },
    categoryCodeChange(item, list) {
      item.categoryName = [];
      item.categoryCode.forEach(cg=>{
        list.forEach(items=> {
          if(items.categoryCode == cg){
            item.categoryName.push(items.categoryName);
          }
        });
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 查询岗位列表 */
    getList() {
      if(this.queryParams.dateRange&&this.queryParams.dateRange.length>0){
        this.queryParams.startDate = this.queryParams.dateRange[0];
        this.queryParams.endDate = this.queryParams.dateRange[1];
      }else{
        this.queryParams.startDate = '';
        this.queryParams.endDate = '';
      }
      this.loading = true;
      orderFlowQueryPage(this.queryParams).then((response) => {
        this.postList = response.data.list;
        this.total = response.data.totalSize;
        this.loading = false;

        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 200;
          this.tableHeight = height + "px";
        });
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = { 
        "endDate": "",
        "remark": "",
        "startDate": "",
        "taskType": "MANUAL_RE_RUN",
        "version": this.versionLists[0] ? this.versionLists[0].versionCode : '',
        dateRange: []
      };
      this.resetForm("spuRef");
      this.title = "新增手工重跑台账任务";
      this.open = true;
    },
    /** 修改按钮操作 */
    showChart(row) {
      this.form = { 
        "endDate": "",
        "remark": "",
        "startDate": "",
        "taskType": "MANUAL_RE_RUN",
        "version": "",
        dateRange: []
      };
      this.resetForm("spuRef");
      this.title = "编辑手工重跑台账任务";
      const rowsCopy = JSON.parse(JSON.stringify(row));
      this.form = Object.assign(this.form, rowsCopy);
      this.form.dateRange = [this.form.startDate, this.form.endDate];
      this.open = true;
    },
    showLog(row){
      orderFlowLog(row.id).then(res=>{
        if(res.status==200){
          this.logVisible = true;
          this.operationLogList = res.data.list;
        }
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    submitDataScope() {
      this.$refs["spuRef"].validate((valid) => {
        if (valid) {
          const fnc = this.title === "新增手工重跑台账任务" ? orderFlowAdd : orderFlowUpdate;
          const data = { ...this.form };
          data.startDate = data.dateRange[0];
          data.endDate = data.dateRange[1];
          fnc(data).then((res) => {
            this.title === "新增手工重跑台账任务" ? this.$modal.msgSuccess("新增成功") : this.$modal.msgSuccess("编辑成功");
            this.open = false;
            this.getList();
            
          });
        }
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageIndex;
      delete data.pageSize;
      this.newDownload(
        "/order-flow-task/export",
        data,
        `重跑台账数据_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      this.newDownload(
        "spu/importTemplate",
        {},
        `spu_template_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}
.gyshop{
  padding: 8px 16px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  margin-bottom: 12px;
  width: 460px;
}
.gyTitle{
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}
.totalSize{
  font-size: 14px;
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
  padding-right: 12px;
  color: #333;
}
</style>
<style lang="scss">
.shop-index{
  .el-radio__label{
    font-size: 12px;
  }
}

</style>

