<template>
  <div>
    <Toptitle title="派工">
      <Button @click="goBack" type="primary" ghost style="margin-right:10px;"
        >返回</Button
      >
      <Button
        @click="handleGoPage"
        type="primary"
        ghost
        style="margin-right:10px;"
        >派工单查询</Button
      >
      <Button
        @click="handleDispatchAllOpen"
        type="primary"
        style="margin-right:10px;"
        >全部派工</Button
      >
    </Toptitle>
    <div class="body">
      <div class="header">
        <Tabs v-model="currencyTag" @on-click="handleProcedureChange">
          <TabPane
            v-for="item in basicsProcedureList"
            :key="item.id"
            :label="item.title"
            :name="item.id + ''"
          />
        </Tabs>
      </div>
      <div class="content">
        <Table
          :columns="tableColumns"
          border
          max-height="700"
          @on-selection-change="handleSelectionChange"
          :data="tableData"
        >
          <template slot="slotGroup" slot-scope="{ row, index }">
            <Select
              v-model="row.employee_id"
              size="small"
              @on-change="
                (e) =>
                  handleGroupSelect(
                    e,
                    tableData[index],
                    index,
                    tableData[index].employee_id
                  )
              "
              clearable
              style="width: 150px"
            >
              <Option
                v-for="sitem in groupList"
                :key="sitem.id"
                :label="sitem.nickname"
                :value="sitem.id"
              >
              </Option>
            </Select>
          </template>
          <template slot="slotSet" slot-scope="{ row, index }">
            <a style="margin:0 5px" @click="handleSet(row, index)">详情</a>
            <a style="margin:0 5px" @click="handleDispatchConfirm(row, index)"
              >派工</a
            >
          </template>
        </Table>
        <!-- <div class="pageSlotStyle">
          <Page :page-size-opts="[10, 20, 30, 40,100,1000]"
                @on-page-size-change='changeSize'
                @on-change='changePage'
                :current='page_index'
                show-total
                :total="total"
                show-sizer
                :page-size='page_size' />
        </div> -->
      </div>
    </div>
    <Modal v-model="showModal" title="确认派工">
      <Form :label-width="85" ref="forms" :model="dispatchInfo">
        <FormItem label="选择时间">
          <DatePicker
            :options="options"
            style="width:100%;"
            v-model="dispatchTime"
            clearable
            type="daterange"
            split-panels
            placeholder="请选择日期"
          ></DatePicker>
        </FormItem>

        <FormItem label="点工单形式">
          <RadioGroup v-model="dispatchInfo.work_type">
            <Radio :label="1">是</Radio>
            <Radio :label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="日薪" v-if="dispatchInfo.work_type == 1">
          <Input v-model="dispatchInfo.user_salary">
            <span slot="append">元</span>
          </Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="showModal = false">取消</Button>
        <Button type="primary" @click="handleDispatch(subArr, subUrl)"
          >确认</Button
        >
      </div>
    </Modal>
    <Modal v-model="showModalAll" title="全部派工">
      <Table
        :columns="modalTableColumns"
        border
        max-height="700"
        :data="modalTableData"
      >
        <template slot="slotGroup" slot-scope="{ row, index }">
          <Select
            v-model="row.employee_id"
            size="small"
            @on-change="
              (e) =>
                handleGroupSelect(
                  e,
                  modalTableData[index],
                  index,
                  modalTableData[index].employee_id
                )
            "
            clearable
            style="width: 120px"
          >
            <Option
              v-for="sitem in groupList"
              :key="sitem.id"
              :label="sitem.nickname"
              :value="sitem.id"
            >
            </Option>
          </Select>
        </template>
      </Table>
      <div slot="footer">
        <Button @click="showModalAll = false">取消</Button>
        <Button type="primary" @click="handleDispatchAllConfirm">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  name: "",
  components: {},
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      tableColumns: [
        // { title: '全选', type: 'selection', align: 'center', minWidth: 60 },
        { title: "工序", align: "center", key: "title", minWidth: 150 },
        { title: "部件总数", align: "center", key: "num", minWidth: 150 },
        {
          title: "班组",
          align: "center",
          key: "",
          minWidth: 150,
          slot: "slotGroup",
        },
        {
          title: "操作",
          align: "center",
          key: "",
          minWidth: 100,
          slot: "slotSet",
        },
      ],
      modalTableColumns: [
        { title: "工序", align: "center", key: "title", minWidth: 150 },
        { title: "部件总数", align: "center", key: "num", minWidth: 150 },
        {
          title: "班组",
          align: "center",
          key: "",
          minWidth: 150,
          slot: "slotGroup",
        },
      ],
      modalTableData: [{}],
      tableData: [{}],
      page_index: 1,
      page_size: 10,
      total: 0,
      basicsProcedureList: [],
      groupList: [],
      currencyTag: "1",
      dispatchTime: [],
      selected: [],
      showModal: false,
      showModalAll: false,
      options: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
      dispatchInfo: {},
      subArr: [],
      subUrl: "",
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 获取工序分类列表
    this.axios({ method: "get", url: "/api/basics_procedure_index" })
      .then((res) => {
        (this.basicsProcedureList = res.data.data),
          (this.currencyTag =
            localStorage.getItem("dispatchTag") || this.currencyTag + "");
      })
      .catch((err) => {});
    //获取班组列表
    this.axios("/api/employee_list", { params: { type: 3 } }).then(
      (res) => (this.groupList = res.data)
    );
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.axios({
        method: "get",
        url: "/api/order_produce_list",
        params: {
          basics_procedure_id:
            localStorage.getItem("dispatchTag") || this.currencyTag,
        },
      })
        .then((res) => {
          this.tableData = res.data;
          this.tableData.forEach((element) => {
            element.produce_id = element.id;
            element.employee_id ? "" : (element.employee_id = "");
          });
          this.$forceUpdate();
        })
        .catch((err) => {});
    },
    goBack() {
      this.$router.go(-1);
    },
    handleGoPage() {
      this.$router.push({ path: "/cms/Dispatching/DispatchedList" });
    },
    handleSet(row, index) {
      this.$router.push({
        path: "/cms/Dispatching/DispatchingDetail",
        query: {
          produce_id: row.id,
        },
      });
    },
    handleDispatchConfirm(row, index) {
      if (row.employee_id) {
        this.selected = [row];
        this.showModal = true;
        this.subArr = JSON.parse(JSON.stringify(this.selected));
        this.subUrl = "/api/order_produce_pull_all";
      } else {
        this.$Message.warning("请选择班组");
      }
    },
    handleDispatch(target, url) {
      if (!this.dispatchTime[0]) {
        this.$Message.warning("请选择时间");
      } else {
        this.dispatchInfo.start_time = new Date(this.dispatchTime[0])
          .toLocaleDateString()
          .replace(/\//g, "-");
        this.dispatchInfo.end_time = new Date(this.dispatchTime[1])
          .toLocaleDateString()
          .replace(/\//g, "-");
        target.forEach((element) => {
          element.start_time = this.dispatchInfo.start_time;
          element.end_time = this.dispatchInfo.end_time;
          element.work_type = this.dispatchInfo.work_type;
          element.user_salary = this.dispatchInfo.user_salary || "";
        });
        this.axios({
          method: "post",
          url,
          data: {
            ...target,
          },
        })
          .then((res) => {
            if (res.code == 200) {
              this.showModal = false;
              this.$Message.success(res.msg || "操作成功");
              this.initData();
              this.dispatchInfo = {};
              this.dispatchTime = [];
            }
          })
          .catch((err) => {});
      }
    },
    handleDispatchAllConfirm() {
      let flag = true;
      this.modalTableData.forEach((element) => {
        if (!element.employee_id || element.employee_id <= 0) {
          flag = false;
        }
      });
      if (flag) {
        (this.showModalAll = false), (this.showModal = true);
        this.subArr = JSON.parse(JSON.stringify(this.modalTableData));
        this.subUrl = "/api/all_order_produce_pull";
      } else {
        this.$Message.warning("请选择班组");
      }
    },
    handleDispatchAllOpen() {
      console.log(localStorage.getItem("dispatchTag"));
      console.log("this.currencyTag :>> ", this.currencyTag);
      this.axios
        .get("/api/get_all_order_produce", {
          params: {
            basics_procedure_id:
              localStorage.getItem("dispatchTag") | this.currencyTag,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.modalTableData = res.data;
            this.modalTableData.forEach((element) => {
              element.produce_id = element.id;
            });
            this.showModalAll = true;
          }
        });
    },
    changePage(e) {
      this.page_index = e;
      this.initData();
    },
    changeSize(e) {
      this.page_size = e;
      this.initData();
    },
    handleProcedureChange(val) {
      this.selected = [];
      this.currencyTag = val;
      localStorage.setItem("dispatchTag", val);
      this.initData();
    },
    handleSelectionChange(selection) {
      this.selected = selection;
    },
    handleGroupSelect(e, row, index, value) {
      // if (this.selected.length > 0) {
      //   this.selected.forEach(element => {
      //     if (element.id == row.id) {
      //       element.employee_id = value
      //     }
      //   });
      // }
      row.employee_id = e;
    },
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="scss" scoped>
.pageSlotStyle {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
/deep/ .ivu-table-wrapper {
  overflow: visible;
}
</style>
