<template>
  <!-- 保养计划列表页 -->
  <div class="sys-box knowledge-box">
    <div class="sys-operate">
      <el-button type="primary" v-has="'upkeep:plan:add'" @click="add()">新增</el-button>
      <el-button type="primary" v-has="'upkeep:plan:remove'" @click="remove()" :disabled="btnDelDisabled">删除</el-button>
      <el-button type="primary" v-has="'upkeep:plan:import'" @click="importFile()">导入</el-button>

      <!-- <el-button
        type="primary"
        v-has="'upkeep:plan:remove'"
        @click="reback()"
        :disabled="btnDelDisabled"
        >撤回</el-button
      > -->
      <!-- <el-button
        type="primary"
        v-has="'upkeep:plan:startUsing'"
        @click="startUsing()"
        :disabled="btnDelDisabled"
        >启用</el-button
      >
      <el-button
        type="primary"
        v-has="'upkeep:plan:forbidden'"
        @click="forbidden()"
        :disabled="btnDelDisabled"
        >禁用</el-button
      > -->
      <!-- <el-button type="primary" @click="execution()" :disabled="btnOtherDisabled">保养执行</el-button> -->
    </div>
    <div class="sys-search">
      <el-form inline class="form_item_search_out">
        <div class="form_item_input_out">
          <el-form-item label="配送单号" style="width:22%" class="form_item-inline">
            <el-input v-model="search_data.psdh" placeholder="配送单号"></el-input>
          </el-form-item>
          <el-form-item label="订单编号" style="width:22%" class="form_item-inline">
            <el-input v-model="search_data.ddbh" placeholder="订单编号"></el-input>
          </el-form-item>
          <!-- <el-form-item label="区域" style="width:22%" class="form_item-inline">
            <el-select
              v-model="search_data.qyid"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in qyList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="记录类型"
            style="width:22%"
            class="form_item-inline"
          >
            <el-select
              v-model="search_data.jllxid"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in jllxList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <btn-input
              :valueText.sync="search_data.engineerName"
              :valueId.sync="search_data.engineerId"
              :chooseVisible.sync="chooseUserVisible"
            ></btn-input>
          </el-form-item> -->
          <el-form-item label="状态" style="width:22%" class="form_item-inline">
            <el-select v-model="search_data.zt" clearable placeholder="请选择">
              <el-option v-for="item in ztList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="服务单号" style="width:22%" class="form_item-inline">
            <el-input v-model="search_data.fwdh" placeholder="服务单号"></el-input>
          </el-form-item>
          <el-form-item label="销售单号" style="width:22%" class="form_item-inline">
            <el-input v-model="search_data.xsdh" placeholder="销售单号"></el-input>
          </el-form-item>
          <el-form-item label="操作日期" style="width:34%" class="form_item-inline">
            <el-date-picker v-model="planTime" type="daterange" range-separator="-" start-placeholder="开始日期"
              end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
        </div>
        <div class="form_item_btn_out">
          <el-form-item>
            <el-button type="primary" @click="search()">查询</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="sys-table">
      <el-table border @sort-change="sortChange" v-loading="pictLoading" @row-click="clickRow" ref="tb"
        :data="tableData" @selection-change="handleSelectionChange" :header-cell-style="{
          fontWeight: 'normal',
          textAlign: 'center',
          backgroundColor: '#eceff4',
          color: '#222'
        }">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="zskdh" align="center" width="200" label="配送单号" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" @click="viewDetail(scope.row)">{{
              scope.row.psdh
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="psrq" label="配送日期" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zt" align="center" label="状态" show-overflow-tooltip>
          <template slot-scope="scope">
            {{
              scope.row.zt == 1
                ? "未开始"
                : scope.row.zt == 2
                  ? "对应中"
                  : scope.row.zt == 3
                    ? "已完成"
                    : "--"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="fwdh" align="center" label="服务单号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xsdh" align="center" label="销售单号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="khmc" align="center" label="客户名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="lxr" align="center" label="联系人" show-overflow-tooltip></el-table-column>
        <el-table-column prop="lxdh" align="center" label="联系电话" show-overflow-tooltip></el-table-column>
        <el-table-column prop="dz" label="地址" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="wlfs" align="center" label="物流方式"></el-table-column>
        <el-table-column prop="wldh" align="center" label="物流单号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ddbh" align="center" label="订单编号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ddsl" align="center" label="订单数量" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cjry" align="center" label="创建人员" show-overflow-tooltip></el-table-column>
        <el-table-column prop="bz" align="center" label="备注" show-overflow-tooltip></el-table-column>
      </el-table>
    </div>
    <div class="sys-pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="search_data.pageno" :page-sizes="pageSizes" :page-size="search_data.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <!-- 选择负责人-->
    <!-- <dialogChooseSingleUser
      :visible.sync="chooseUserVisible"
      @change="getUser"
    ></dialogChooseSingleUser> -->
    <!-- <chooseSbjh :visible.sync="chooseSbjhVisible" /> -->
    <dialog-import-file
      v-if="showUserImportDialog"
      :visible.sync="showUserImportDialog"
      title="售后管理批量导入"
      source="wlps"
      :upload-data="{ type: 'user' }"
      @success="handleUserImportSuccess"
      @close="showUserImportDialog = false"
    />
  </div>
</template>

<script>

import { formatDateTime } from "@/utils/tools.js";
import DialogImportFile from '@/components/Dialog/dialogImportFile.vue';
// import btnInput from "@/components/btnInput.vue";
// import chooseSbjh from "./components/chooseSbjh.vue";
// import dialogChooseSingleUser from "@/components/System/dialogChooseSingleUser";
let api = {
  page: "/apis/mdh/wlps/pageList",
  del: "/apis/mdh/wlps/del",
  edit: "/apis/mdh/wlps/edit"
};
export default {
  name: "wlps",
  components: {
    DialogImportFile
    // btnInput
    // dialogChooseSingleUser
    // chooseSbjh
  },
  data() {
    return {
      showUserImportDialog:false,
      ztList: [
        {
          name: "未开始",
          id: 1
        },
        {
          name: "对应中",
          id: 2
        },
        {
          name: "已完成",
          id: 3
        }
      ],
      qyList: [],
      total: 0, //总条数
      pageSizes: [10, 20, 50], //每页展示多少条
      search_data: {
        pageno: 1,
        pagesize: 10
      },

      planTime: "",

      statusList: [], //计划状态
      getUserList: [], //用户

      btnDelDisabled: true,
      btnOtherDisabled: true,
      chooseUserVisible: false,
      chooseSbjhVisible: false,
      rowIds: [],
      tableData: [],
      dialogVisible: false,
      pictLoading: false,
      qyList: [],
      jllxList: [],
      dywzList: []
    };
  },
  created() {
    var _this = this;
    document.onkeydown = e => {
      if (e.key === "Enter") {
        _this.search();
      }
    };
  },
  mounted() {
    //let user = JSON.parse(sessionStorage.getItem("userInfo"));
    //console.log(user);
    //this.search_data.engineerId = user.userId;
    this.getList();
    // this.initData();
  },
  methods: {
    handleUserImportSuccess(response, file, fileList) {
      this.getList()
    },
    importFile(){
      this.showUserImportDialog = true
    },
    async reback() {
      if (this.rowIds.length > 0) {
        let r = this.rowIds[0];
        let pass = r.zt == 3 ? true : false;
        if (pass) {
          const params = {
            id: r.id,
            zt: 2,
            zczt: 0
          };
          const res = await this.$api.yxkAPI.yxkPost(api.edit, params);
          if (res.code == 0) {
            this.$message({
              message: "撤回成功",
              type: "success"
            });
            this.getList();
          }
        } else {
          this.$message({
            message: "非已提交状态不能撤回",
            type: "warning"
          });
          return false;
        }
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
        return false;
      }
    },
    /**
     * 获取选择的负责人
     */
    getUser(val) {
      if (val) {
        this.$set(this.search_data, "engineerName", val.name);
        this.$set(this.search_data, "engineerId", val.id);
      } else {
        this.$set(this.search_data, "engineerName", "");
        this.$set(this.search_data, "engineerId", "");
      }
    },
    sortChange({ column, prop, order }) {
      let j = { column, prop, order };
      let order_ = j.order == "ascending" ? "asc" : "desc";
      this.$set(this.search_data, "sort", j.prop);
      this.$set(this.search_data, "order", order_);
      this.getList();
    },
    clickRow(row) {
      this.$refs.tb.toggleRowSelection(row);
    },
    initData() {
      Promise.all([
        this.$api.dictAPI.getDictsByType("qy"),
        this.$api.dictAPI.getDictsByType("jllx"),
        this.$api.dictAPI.getDictsByType("dywz")
      ])
        .then(([r1, r2, r3]) => {
          if (r1.code === 0) {
            this.qyList = r1.datas;
          }
          if (r2.code == 0) {
            this.jllxList = r2.datas;
          }
          if (r3.code == 0) {
            this.dywzList = r3.datas;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    /**
     * 获取列表
     */
    getList() {
      this.pictLoading = true;
      if (this.planTime) {
        this.search_data.startTime = formatDateTime(this.planTime[0]);
        this.search_data.endTime = formatDateTime(this.planTime[1]);
      } else {
        this.search_data.startTime = null;
        this.search_data.endTime = null;
      }
      this.$api.yxkAPI
        .yxkPost(api.page, this.search_data)
        .then(res => {
          this.pictLoading = false;
          if (res.data) {
            this.total = res.data.total;
            let result = res.data.records;
            this.tableData = result;
          } else {
            this.total = 0;
            this.tableData = [];
          }
        })
        .catch(r => {
          console.log(r);
        });
    },
    /**
     * 查询
     */
    search() {
      this.search_data.pageno = 1;
      this.getList();
    },
    // 上下分页
    handleCurrentChange(val) {
      this.search_data.pageno = val;
      this.getList();
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.search_data.pagesize = val;
      this.getList();
    },
    /**
     * 新增
     */
    add() {
      this.$router.push({
        path: "/khgxgl/wlps-add",
        query: {
          t: Date.now()
        }
      });
    },
    /**查看明细 */
    viewDetail(r) {
      if (r.zt == 2) {
        this.$router.push({
          path: "/khgxgl/wlps-add",
          query: { id: r.id, t: Date.now() }
        });
      } else {
        this.$router.push({
          path: "/khgxgl/wlps-add",
          query: { id: r.id, t: Date.now() }
        });
      }
    },

    /**
     * 保养执行
     */
    execution() {
      // let id = this.rowIds[0].reventId;
      // this.$router.push({
      //   path: "/upkeep/record",
      //   query: { id: id }
      // });
    },
    /**
     * 删除
     */
    remove() {
      let ids = [];
      this.rowIds.forEach(item => {
        ids.push(item.id);
      });
      this.$confirm("确认删除选中的数据吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.yxkAPI
          .yxkPost(api.del, ids)
          .then(res => {
            console.log(res);
            if (res.code == 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.getList();
            } else {
              this.$message({
                message: res.msg ? res.msg : "删除失败，请重试",
                type: "error"
              });
            }
          })
          .catch(error => {
            this.$message({
              message: "删除失败，请重试",
              type: "error"
            });
          });
      });
    },
    /**
     * 启用
     */
    startUsing() {
      let ids = [];
      this.rowIds.forEach(item => {
        ids.push(item.id);
      });
      this.$confirm("确认启用选中的保养计划吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.upkeepPlanAPI
          .startUsing({ ids: ids })
          .then(res => {
            console.log(res);
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.getList();
            } else {
              this.$message({
                message: res.msg ? res.msg : "启用失败，请重试",
                type: "error"
              });
            }
          })
          .catch(error => {
            this.$message({
              message: "启用失败，请重试",
              type: "error"
            });
          });
      });
    },
    /**
     * 禁用
     */
    forbidden() {
      let ids = [];
      this.rowIds.forEach(item => {
        ids.push(item.id);
      });
      this.$confirm("确认禁用选中的保养计划吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.upkeepPlanAPI
          .forbidden({ ids: ids })
          .then(res => {
            console.log(res);
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.getList();
            } else {
              this.$message({
                message: res.msg ? res.msg : "禁用失败，请重试",
                type: "error"
              });
            }
          })
          .catch(error => {
            this.$message({
              message: "禁用失败，请重试",
              type: "error"
            });
          });
      });
    },
    /**
     * 处理选中
     */
    handleSelectionChange(val) {
      this.rowIds = val;
      this.setBtn(val);
    },
    /**
     * 控件操作按钮状态
     */
    setBtn(val) {
      let isFlag = true;
      let isDelFlag = true;
      if (val.length > 0) {
        isDelFlag = false;
        if (val.length == 1) {
          isFlag = false;
        }
      } else {
        isFlag = true;
        isDelFlag = true;
      }
      this.btnDelDisabled = isDelFlag;
      this.btnOtherDisabled = isFlag;
    }
  }
};
</script>

<style scoped></style>
