<template>
  <div class="approval-dialog">
    <div id="approvalModalBox"></div>
    <a-modal class="approval-main-dialog" v-model:visible="props.applyArtworkVisiable" @ok="handleOk" @cancel="handleOk" :getContainer="getContainer">
      <template #title>
        <div class="title">画作分配</div>
      </template>
      <template #closeIcon> <img src="@/assets/image/approval/close.png" /></template>
      <a-form
        class="form-dialog"
        ref="addForm"
        :model="formState"
        name="basic"
        labelAlign="left"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off">
        <a-form-item :colon="false" label="提交人" name="username">{{ Local.get("userInfo").NickName || "" }} </a-form-item>
        <a-form-item :colon="false" label="分配人" name="username">
          <a-space>
            <a-select
              v-model:value="state.checkDept"
              style="width: 120px"
              placeholder="请选择部门"
              :fieldNames="{
                label: 'Name',
                value: 'Name',
              }"
              @change="selectDept"
              :options="state.giveDepOpt"></a-select>
            <a-select
              v-model:value="state.checkJob"
              style="width: 120px"
              placeholder="请选择岗位"
              :fieldNames="{
                label: 'Name',
                value: 'Name',
              }"
              @change="selectJob"
              :options="state.giveJobOpt"></a-select>
            <a-select
              v-model:value="state.givePerson"
              placeholder="请选择人员"
              :fieldNames="{
                label: 'Name',
                value: 'ID',
              }"
              mode="multiple"
              style="width: 120px"
              :options="state.givePerOpt"></a-select>
          </a-space>
        </a-form-item>

        <a-form-item :colon="false" label="领取时间" name="ReceivedAt" :rules="[{ required: true, trigger: 'blur', message: '请选填写日期' }]">
          <a-date-picker v-model:value="formState.ReceivedAt" valueFormat="YYYY-MM-DD" />
        </a-form-item>

        <div class="tags">
          <span style="margin-left: 15px" v-for="item in state.selectedRows"
            ><close-circle-outlined @click="closeTag(item)" />{{ item.ArtworkName }}</span
          >
        </div>
        <a-form-item :colon="false" label="申请内容" name="workContent">
          <div class="action-table">
            <div>
              <span style="font-size: 16px; margin-right: 10px">请选择画家画作</span>
              <a-select
                v-model:value="state.ArtistName"
                show-search
                style="width: 150px; margin-right: 10px"
                :getPopupContainer="getContainer"
                placeholder="可搜索"
                :fieldNames="{ label: 'Name', value: 'Name' }"
                :options="state.options"
                @change="handleAritstChange"></a-select>
            </div>
            <a-switch
              v-model:checked="giveChecked"
              @change="
                (val) => {
                  val ? getWorkList(1) : getWorkList(-1);
                }
              "
              checked-children="可分配画作"
              un-checked-children="全部画作" />
          </div>
          <a-table
            class="artwork-table"
            :rowKey="(record) => record.Id"
            :columns="state.workColumns"
            :row-selection="{
              onChange: onSelectChange,
              selectedRowKeys: state.selectedRowKeys,
              checkStrictly: false,
              hideSelectAll: true,
              getCheckboxProps: (record) => ({
                disabled: !(record.StorageStatus === 1 && record.SaleStatus < 6),
              }),
            }"
            :data-source="state.workTableData"
            :scroll="{ y: 245 }"
            :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'HdPic'">
                <img style="height: 40px; width: 40px" :src="record.HdPic + '?x-oss-process=image/resize,w_40,h_40'" />
              </template>
            </template>
          </a-table>
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="button-group">
          <a-button @click="handleOk" class="cancel-btn">取消</a-button>
          <a-button @click="save" class="save-btn">分配</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, defineProps, defineEmits, getCurrentInstance, nextTick } from "vue";
import { CloseCircleOutlined } from "@ant-design/icons-vue";
import { processError, processSuccess, processWarning } from "@/utils/helper/message";
import { Local } from "@/utils/storage.js";
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;
const formState = reactive({
  Type: "",
  Content: "",
  ApplicationsNum: null,
  ReceivedAt: "",
});
const addForm = ref();
const giveChecked = ref(false);
const state = reactive({
  ArtistName: "",
  options: [],
  ArtistUID: "",
  workColumns: [
    {
      title: "画作名称",
      dataIndex: "ArtworkName",
      align: "center",
    },
    {
      title: "画家名称",
      dataIndex: "ArtistName",
      align: "center",
    },
    {
      title: "图片",
      dataIndex: "HdPic",
      align: "center",
      key: "HdPic",
    },
    {
      title: "库存状态",
      dataIndex: "storageTxt",
      align: "center",
    },
    {
      title: "销售状态",
      dataIndex: "saleTxt",
      align: "center",
    },
  ],
  workTableData: [],
  selectedRowKeys: [],
  selectedRows: [],
  ApprovalUsers: null,
  CopyUsers: null,
  givePerson: [],
  giveDepOpt: [],
  checkJob: null,
  giveJobOpt: [],
  checkDept: null,
  givePerOpt: [],
  saleDict: {
    0: "未入库",
    1: "仓库",
    2: "数字化中",
    3: "鉴证中",
    4: "数字化已完成",
    5: "鉴证已完成",
    6: "待销售",
    7: "出库",
    8: "已售",
  },
  storageDict: { 0: "未入库", 1: "仓库", 2: "数字化", 3: "鉴证", 4: "仓库" },
});
const props = defineProps({
  // 抄送人弹窗显示
  applyArtworkVisiable: {
    type: Boolean,
    default: false,
  },
});
const selectDept = (value, selectedOptions) => {
  state.givePerson = [];
  state.checkJob = null;
  state.giveJobOpt = selectedOptions.Children;
};
const selectJob = (value, selectedOptions) => {
  state.givePerson = [];
  state.givePerOpt = selectedOptions.Children;
};
// 获取画家列表
const getArtistList = () => {
  $request.HTTP.artist
    .artistBaseInfoList({ Keyword: "", Page: 1, PageSize: 99999999 })
    .then((res) => {
      if (res.status == 0) {
        state.options = res.data.Data;
      } else {
      }
    })
    .catch((e) => {});
};
const handleAritstChange = (val, opt) => {
  state.ArtistUID = opt.Uid;
  nextTick(() => {
    state.selectedRows = [];
    state.selectedRowKeys = [];
  });
  getWorkList();
};
// 获取部门人员
const getDeptUserList = () => {
  $request.HTTP.approval
    .getdepartmentList({})
    .then((res) => {
      if (res.status === 0) {
        state.giveDepOpt = res.data;
      }
    })
    .catch((e) => {});
};
// 选中
const onSelectChange = (selectedRowKeys, rows) => {
  state.selectedRows = rows;
  state.selectedRowKeys = selectedRowKeys;
};
// 关闭
const closeTag = (tag) => {
  const id = JSON.parse(JSON.stringify(tag.Id));
  const tags = state.selectedRowKeys.filter((item) => item != id);
  const rows = state.selectedRows.filter((item) => item.Id != id);
  nextTick(() => {
    state.selectedRows = rows;
    state.selectedRowKeys = tags;
  });
};
const aprovalTypeOpt = ref([]);
// type = 1全部，2可选
const getWorkList = (StorageStatus = -1) => {
  $request.HTTP.artwork
    .artworkList({
      ArtistUID: state.ArtistUID,
      page: 1,
      pageSize: 99999,
      StorageStatus: StorageStatus,
    })
    .then((res) => {
      if (res.status === 0) {
        state.workTableData = res.data.Data;
        state.workTableData.forEach((v) => {
          v.storageTxt = state.storageDict[v.StorageStatus];
          v.saleTxt = state.saleDict[v.SaleStatus];
        });
      } else {
        processError(res.msg);
      }
    })
    .catch((e) => {});
};
const save = () => {
  addForm.value
    .validate()
    .then(() => {
      let data = {};
      // 提取画作名称和画作ID，并组成一个对象数组
      let ArtworkNames = [];
      state.selectedRows.forEach((v) => {
        ArtworkNames.push({
          ArtworkName: v.ArtworkName,
          ArtworkId: v.Id,
        });
      });

      if (state.givePerson.length < 1) {
        processWarning("请指定分配人");
        return;
      }
      if (state.selectedRows.length < 1) {
        processWarning("请至少选择一副画作");
        return;
      }
      data = {
        AllotUids: state.givePerson,
        ActionType: 3,
        PostName: state.checkJob,
        ArtworkNames: ArtworkNames,
        ArtworkIds: state.selectedRowKeys,
        ReceiveDate: formState.ReceivedAt,
      };

      $request.HTTP.approval
        .giveArtwork(data)
        .then((res) => {
          if (res.status === 0) {
            handleOk();
            reset();
            processSuccess("分配成功");
          } else {
            processError(res.msg);
          }
        })
        .catch((e) => {});
    })
    .catch((error) => {});
};

// 重置
const reset = () => {
  addForm.value.resetFields();
  state.checkDept = null;
  state.checkJob = null;
  state.givePerson = [];
};
const emit = defineEmits("applyArtworkHandleOk");
// 改变modal根节点 解决打开后出现padding
const getContainer = () => {
  return document.getElementById("approvalModalBox");
};
// 关闭回调
const handleOk = (e) => {
  emit("applyArtworkHandleOk");
};
const themeTxt = ref("");
const value1 = ref("lucy");
const focus = () => {
  console.log("focus");
};
// 选项回调
const handleChange = (value) => {
  console.log(`selected ${value}`);
};
watch(
  () => props.applyArtworkVisiable,
  (newValue, oldValue) => {
    if (newValue) {
      getDeptUserList();
      // getWorkList();
      getArtistList();
    }
  }
);
</script>

<style lang="scss" scoped>
.title {
  text-align: center;
  margin: 0;
  color: $theme-primary;
}
.approval-box {
  display: flex;
  width: 300px;
  align-items: flex-end;
  text-align: left;
  color: $theme-primary;
  margin-bottom: 25px;
}
.form-label {
  font-size: 16px;
  color: $theme-primary;
}
.tags {
  background-color: #cfcad8;
  width: 422px;
  margin-left: 109px;
}
.textarea {
  background-color: #cfcad8;
}
textarea::-webkit-input-placeholder {
  color: #ffffff !important;
}
.action-table {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.button-group {
  text-align: center;

  .cancel-btn {
    width: 123px;
    border-radius: 20px;
    background: #eeeaf7;
    margin-right: 10px;
    color: $theme-primary;
  }
  .save-btn {
    width: 123px;
    border-radius: 20px;
    background: $theme-primary;
    color: #ffff;
  }
}
.artwork-table {
  :deep(.ant-table) {
    border-radius: 1px;
    overflow: hidden;
    color: $basic-black;
  }
  :deep(.ant-table-container) {
    border: 1px solid #cfcad8;
  }
  :deep(.ant-table-thead > tr > th) {
    padding: 4px 4px;
  }
  :deep(.ant-table-tbody > tr > td) {
    padding: 4px 16px;
  }
  :deep(.ant-table-thead > tr > th) {
    background: #cfcad8 !important;
    border-bottom: 1px solid #dfd7f2;
    font-weight: bolder !important;
    color: #7161a5 !important;
  }
}
:deep(.ant-form-item-label > label) {
  color: $theme-primary;
  font-size: 16px;
  font-weight: 400;
}
:deep(.ant-form-item) {
  color: $theme-primary;
  font-size: 16px;
  font-weight: 200;
  .ant-select {
    background-color: #e3dfea;
  }
  .ant-input {
    background-color: #e3dfea;
  }
  .ant-select-arrow .anticon {
    color: $theme-primary;
  }
}
</style>
<style lang="scss">
.approval-main-dialog {
  width: 700px !important;
  .ant-modal-body {
    height: 650px !important;
    overflow-y: scroll;
  }
}
</style>
