<template>
  <div>
    <div class="select-content">
      <Button type="primary" @click="cloneTemplate">克隆调令</Button>
      <el-date-picker
        size="small"
        :clearable="false"
        v-model="date"
        value-format="yyyy-MM-dd"
        placeholder="日期选择"
        format="yyyy-MM-dd"
        style="width: 130px;margin-left: 6px;"
      ></el-date-picker>
      <Select clearable v-model="select.filter[2].value" placeholder="请选择类别" style="width: 130px;margin-left: 6px;">
        <Option v-for="item in abilities" :value="item.value">{{ item.key }}</Option>
      </Select>
      <Select clearable v-model="select.filter[1].value" placeholder="请选择范围" style="width: 130px;margin-left: 6px;">
        <Option v-for="item in areas" :value="item.value">{{ item.key }}</Option>
      </Select>
      <Select clearable v-model="select.filter[3].value" placeholder="请选择点位" style="width: 130px;margin-left: 6px;">
        <Option v-for="item in equipmentList" :value="item.id">{{ item.name }}</Option>
      </Select>
      <Input style="width: 140px;margin-left: 6px;" clearable v-model="select.filter[0].value" placeholder="搜索内容"/>
      <Button style="margin-left: 6px;" type="primary" @click="getDispatches">搜索</Button>
      <Button type="primary" @click="pickNoDistribute">勾选当日未下发</Button>
      <Button type="primary" @click="distributeTransfers">批量下发</Button>
    </div>

    <Table
      ref="listTable"
      style="margin-top: 16px;"
      border
      :loading="loading"
      :columns="columns"
      :data="mergeData"
      stripe
      :span-method="objectSpanMethod"
    ></Table>

<!--    <el-pagination-->
<!--      class="pagination"-->
<!--      @size-change="e => {-->
<!--        select.page_size = e;-->
<!--        select.page = 1;-->
<!--        getDispatches();-->
<!--      }"-->
<!--      @current-change="e => {-->
<!--        select.page = e;-->
<!--        getDispatches();-->
<!--      }"-->
<!--      :current-page="select.page"-->
<!--      :page-sizes="[10, 20, 30, 40]"-->
<!--      :page-size="select.page_size"-->
<!--      layout="total, prev, pager, next, jumper, sizes"-->
<!--      :total="total">-->
<!--    </el-pagination>-->
    <callback ref="callback" @refresh="getDispatches"></callback>
    <dialoger
      :table-name="customForm.tableName"
      :form-info="form"
      ref="dialog"
      @refresh="$refs['xyTable'].getTableData()"
    >
    </dialoger>
  </div>
</template>

<script>
import callback from "@/views/order/component/callback.vue";
import { deepCopy } from "@/utils";
import { index, destroy, save } from "@/api/system/baseForm";
import { mergeTableRow }  from "@/utils/mergeTableRow";
import { getOaToken } from "@/api/other";
import dialoger from "@/views/component/dialog.vue";
import {show} from "@/api/system/customForm";
import {listdept} from "@/api/system/department";
import {getparameter} from "@/api/system/dictionary";

export default {
  components: {
    dialoger,
    callback
  },
  inject: ["equipments"],
  data() {
    return {
      oaToken: "",
      window: {
        width: 0,
        height: 0,
        top: 0,
        left: 0
      },
      loading: false,
      areas: [],
      abilities: [],
      date: this.$moment().format("YYYY-MM-DD"),
      select: {
        table_name: 'transfers',
        page: 1,
        page_size: 999,
        sort_name: 'equipment_id',
        filter: [
          {
            key: "content",
            op: "like",
            value: ""
          },
          {
            key: "area",
            op: "eq",
            value: ""
          },
          {
            key: "leibie",
            op: "eq",
            value: ""
          },
          {
            key: "equipment_id",
            op: "eq",
            value: ""
          },
          {
            key: "status",
            op: "eq",
            value: 1
          }
        ]
      },
      total: 0,
      data: [],
      columns: [
        {
          width: 54,
          type: "selection"
        },
        {
          title: "范围",
          width: 140,
          key: "area",
          align: "center",
          render: (h, { row, index }) => {
            let area = row.equipment_id_equipments_id_relation ? row.equipment_id_equipments_id_relation.area : "";
            let text = this.areas.find(i => i.value === area)?.key
            return h('span',text)
          }
        },
        {
          title: "点位",
          width: 240,
          key: "equipment_id",
          align: "center",
          render: (h, { row, index }) => {
            let text = row.equipment_id_equipments_id_relation ? row.equipment_id_equipments_id_relation.name : "";
            return h('span',text);
          },
        },
        {
          title: '类别',
          width: 100,
          key: 'leibie',
          align: 'center',
          render: (h,{ row }) => h('span', (this.abilities.find(i => i.value === row.leibie))?.key)
        },
        {
          title: "调令日期",
          width: 120,
          align: 'center',
          render: (h,{ row }) => h('span', this.$moment(row.start_time).format('YYYY-MM-DD'))
        },
        {
          title: "开启时间",
          width: 100,
          align: "center",
          key: "start_time",
          render: (h,{ row }) => h('span', this.$moment(row.start_time).format('HH:mm'))
        },
        {
          title: "持续时间",
          width: 100,
          align: "center",
          key: "last",
          render: (h,{ row }) => h('span', this.$moment(row.end_time).diff(this.$moment(row.start_time),'hours',true).toFixed(2) + '小时')
        },
        {
          title: "结束时间",
          width: 100,
          align: "center",
          key: "end_time",
          render: (h,{ row }) => h('span', this.$moment(row.end_time).format('HH:mm'))
        },
        {
          title: "调令内容",
          minWidth: 200,
          key: "content",
          align: "left",
        },
        {
          title: "调令等级",
          width: 140,
          key: "level",
          align: "center",
          render: (h, { row }) => {
            let type = new Map([
              [1,'一般'],
              [2,'紧急']
            ])
            return h('span',type.get(row.level));
          },
        },
        {
          title: "操作",
          minWidth: 310,
          key: "operate",
          render: (h, { row, index }) => {
            const btnMap = new Map([
              ['delete',h(
                "Poptip",
                {
                  props: {
                    title: "确认要删除吗？",
                    confirm: true,
                    transfer: true,
                  },
                  on: {
                    ["on-ok"]: (e) => {
                      destroy({
                        table_name: 'transfers',
                        id: row.id
                      }).then(res => {
                        this.$message({
                          type: 'success',
                          message: '删除成功'
                        })
                        this.getDispatches();
                      })
                    },
                  },
                },
                [
                  h(
                    "Button",
                    {
                      style: {
                        'margin-left': "6px"
                      },
                      props: {
                        type: "error",
                        size: "small",
                      },
                    },
                    "删除"
                  ),
                ]
              )],
              [
                'edit',h(
                  "Button",
                  {
                    style: {
                      'margin-left': '6px'
                    },
                    props: {
                      type: "primary",
                      size: "small",
                    },
                    on: {
                      click:() => {
                        this.$refs['dialog'].setId(row.id);
                        this.$refs['dialog'].setType('editor');
                        this.$refs['dialog'].show();
                      }
                    }
                  },
                  "编辑"
              ),
              ],
              ['oa',h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  on: {
                    'click': async () => {
                      if (!this.oaToken) {
                        this.oaToken = (await getOaToken()).oatoken
                      }
                      let jsonInfo = {
                        'title': row.equipment_id_equipments_id_relation?.name,
                        '65aa1a59e408c': row.start_time,
                        '65aa1a7e4109d': row.level,
                        '65aa1a442705f': row.content
                      }
                      let url =
                        `${process.env.VUE_APP_OA_URL}/admin/flow/create/34?diaoling_oatoken=${this.oaToken}&out_diaoling_id=${row.id}&default_json=${JSON.stringify(jsonInfo)}`
                      window.open(url, 'diaoling',
                        `top=${this.window.top},left=${this.window.left},width=${this.window.width},height=${this.window.height},location=0`
                      )
                    }
                  }
                },
                "发起流程"
              )],
              ['distribute',h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  on: {
                    'click': () => this.setTransferStatus(2,row)
                  }
                },
                "下发"
              )],
              ['cancel',h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    ghost: true,
                  },
                  on: {
                    'click': () => this.setTransferStatus(0,row)
                  }
                },
                "取消"
              )]
            ])
            const auths = ['distribute','cancel','oa','edit','delete'].filter(item => {
              if (row.status === 0) {
                if (item === 'oa') {
                  return false
                }
              }
              if ([2,3,4,5,6,7].find(i => i === row.status)) {
                if (item === 'delete' || item === 'oa') {
                  return false
                }
              }
              if ([3,4,5,6,7].find(i => i === row.status)) {
                if (item === 'edit') {
                  return false
                }
              }
              if (row.liuchengzhuangtai === 2 || row.liuchengzhuangtai === 3) {
                if (item === 'delete' || item === 'edit') {
                  return false
                }
              }
              if (!(row.status === 1 || row.status === 0)) {
                if (item === 'distribute') {
                  return false
                }
              }
              if (row.status !== 2) {
                if (item === 'cancel') {
                  return false
                }
              }
              return true
            })
            return h('div',{
              style: {
                'display': 'flex'
              }
            },auths.map(i => (btnMap.get(i))));
          },
        },
      ],

      form: [],
      customForm: {
        customFormId: "",
        tableName: "",
      },
    }
  },
  methods: {
    index,
    async getFormDetail () {
      if (this.$route.meta.params?.custom_form) {
        let decode = decodeURIComponent(this.$route.meta.params?.custom_form);
        try {
          let custom_form = JSON.parse(decode);
          this.customForm.customFormId = custom_form.custom_form_id;
          this.customForm.tableName = custom_form.table_name;
          this.select.table_name = custom_form.table_name;
        } catch (err) {
          console.warn(err);
        }
      }
      if (this.$route.meta.params?.select) {
        try {
          this.selectQuery = JSON.parse(
            decodeURIComponent(this.$route.meta.params?.select)
          );
        } catch (err) {
          console.warn(err);
        }
      }

      const res = await show({ id: this.customForm.customFormId }, false);

      //字段处理
      //初始表白名单
      let baseTable = new Map([
        [
          "departments",
          async () => {
            const res = await listdept();
            return res;
          },
        ],
        ["admins", []],
      ]);
      let { fields, relation } = res;
      let fieldRes = fields.sort((a, b) => a.sort - b.sort);
      if (
        !fields ||
        !relation ||
        !fields instanceof Array ||
        !relation instanceof Array
      ) {
        throw new Error("fields或relation格式错误");
      }
      fieldRes?.forEach((i, index) => {
        i._relations = relation.find((j) => j.custom_form_field === i.field);
        if (i.select_item && typeof i.select_item === "object") {
          let keys = Object.keys(i.select_item);
          if (keys.length > 0) {
            i._params = keys.map((key) => {
              return {
                key,
                value: /^\d*$/.test(i.select_item[key])
                  ? Number(i.select_item[key])
                  : i.select_item[key],
              };
            });
          }
        }
        if (i.edit_input === "file" || i.edit_input === "files") {
          return;
        }
        if (i._relations) {
          if (baseTable.get(i._relations.link_table_name)) {
            baseTable
              .get(i._relations.link_table_name)()
              .then((res) => (i._params = res));
          } else {
            i._params = i._relations.parameter_id
              ? getparameter({ id: i._relations.parameter_id }, false).then(
                (res) => {
                  i._params = res.detail;
                }
              )
              : this.index({
                table_name: i._relations.link_table_name,
                page: 1,
                page_size: 9999,
              }).then((res) => {
                i._params = res.data;
              });
          }
        }
      });
      this.form = fields;
    },

    setTransferStatus (status,row) {
      let copyRow = deepCopy(row);
      copyRow.status = status;
      for (let key in copyRow) {
        if (/_relation/g.test(key)) {
          delete copyRow[key]
        }
      }
      save({
        table_name: 'transfers',
        ...copyRow
      }).then(_ => this.getDispatches())
    },

    cloneTemplate () {
      let select = this.$refs['listTable']?.getSelection()?.map((i) => (
        {
          equipment_id: i.equipment_id,
          start_time: this.$moment(i.start_time).format('HH:mm'),
          end_time: this.$moment(i.end_time).format('HH:mm'),
          content: i.content,
          level: i.level,
        }
      ));
      this.$emit("cloneTransfers", select)
      // this.$prompt("请输入模板名称", "模板", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   inputValidator: (value) => {
      //     return !!value;
      //   },
      //   inputErrorMessage: "请输入模板名称",
      // }).then(({ value }) => {
      //   save({
      //     table_name: "transfer_templates",
      //     name: value,
      //     content: JSON.stringify(
      //       this.$refs['listTable']?.getSelection()?.map((i) => ({
      //         equipment_id: i.equipment_id,
      //         start_time: this.$moment(i.start_time).format("HH:mm"),
      //         end_time: this.$moment(i.end_time).format("HH:mm"),
      //         content: i.content,
      //         level: i.level,
      //       }))
      //     ),
      //   }).then((_) => {
      //     this.$message({
      //       type: "success",
      //       message: "保存成功",
      //     });
      //   });
      // });
    },

    async distributeTransfers () {
      let promiseAll = this.$refs['listTable'].getSelection().map(i => {
        for (let key in i) {
          if (/_relation/g.test(key)) {
            delete i[key]
          }
        }
        i.status = 2;
        return save({
          table_name: 'transfers',
          ...i
        })
      })
      const res = await Promise.all(promiseAll)
      this.$message({
        type: 'success',
        message: `下发${res.length}条调令`
      })
      await this.getDispatches();
    },

    pickNoDistribute () {
      this.data = this.data.map(i => {
        i._checked = i.status === 1
        return i
      })
    },

    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const span = column["key"] + "-span";
      if (row[span]) {
        return row[span];
      }
    },

    async getDispatches () {
      try {
        this.loading = true;
        if (this.select.filter.find(i => i.key === 'start_time')) {
          this.select.filter.pop();
        }
        this.select.filter.push({
          key: "start_time",
          op: "like",
          value: this.date
        })
        const res = await index(this.select);
        this.data = res.data;
        this.total = res.total;
        this.loading = false;

        this.$bus.$emit('getDispatches', this.data)
      } catch (e) {
        this.loading = false;
      }
    }
  },
  computed: {
    mergeData() {
      return mergeTableRow({
        data: this.data.map((i) => {
          delete i["equipment_id-span"];
          delete i["area-span"]
          return i;
        }),
        mergeColNames: ["equipment_id","area"], // 需要合并的列，默认合并列相同的数据
        firstMergeColNames: ["equipment_id"], // 受影响的列，只合并以firstMerge为首的同类型数据
        firstMerge: "equipment_id", // 以哪列为基础进行合并，一般为第一列
      });
    },
    equipmentList() {
      return this.equipments() || [];
    },
  },
  watch: {
  },
  created() {
    this.getFormDetail()
    this.getDispatches()
    this.$bus.$on('pickDate',e => (this.date = e,this.getDispatches()))
    this.$bus.$on('yinpaishui',e => (this.abilities = e))
    this.$bus.$on('areas',e => (this.areas = e))
    this.$bus.$on('createdTransfer',_ => (this.getDispatches()))
  },
  destroyed() {
    this.$bus.$off('pickDate')
    this.$bus.$off('areas')
    this.$bus.$off('yinpaishui')
    this.$bus.$off('createdTransfer')
  }
}
</script>

<style scoped lang="scss">
.select-content {
  width: 100%;
  display: flex;
  align-items: center;
}
.pagination {
  display: flex;
  justify-content: center;

  padding: 20px 0;
}
</style>
